Showing posts with label File System. Show all posts
Showing posts with label File System. Show all posts

Tuesday, 19 June 2012

You can open a file in read mode and get FileStream Object for reading a stream.
After getting FileStream object you can read data using "Read" and "ReadByte" methods.
You can open any file i.e Text , Image , doc etc..
After reading the file you need to close the FileStream Object.

Here are example for this.
In this example we open two different "Text" and "Image" format files.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    objFileStreamTxt.Close();

    // Get a filestream for reading a Image file
    System.IO.FileStream objFileStreamImg = System.IO.File.OpenRead(MapPath("computer.jpg"));
    objFileStreamImg.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        objFileStreamTxt.Close()

        ' Get a filestream for reading a Image file
        Dim objFileStreamImg As System.IO.FileStream = System.IO.File.OpenRead(MapPath("computer.jpg"))
        objFileStreamImg.Close()

Here is example of how to read FileStream object using "Read" method. Click Here...

This is very useful .Net Tips which is use in day to day programming life.

You can read file byte data using "Read" Method of FileStream class and get bytes array. You can also say that read bytes array from FileStream object or read bytes array from FILE.

Here are example of this.
In this example We get FileStream of file and read it's byte data , byte data are store in Byte array.
You can also say that this approach is as chunk by chunk reading.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));

    // Set buffer length
    int intBufferLength = 16 * 1024;
    byte[] objBuffer = new byte[intBufferLength];

    int len = 0;

    while ((len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)) != 0)
    {
        // Here objBuffer object has bytes value, Which you can use to write into other stream or other use
        // Here objBuffer object contains intBufferLength length data
    }

    objFileStreamTxt.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))

        ' Set buffer length
        Dim intBufferLength As Integer = 16 * 1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        Dim len As Integer = 0
        len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Here objBuffer object has bytes value, Which you can use to write into other stream or other use
            ' Here objBuffer object contains intBufferLength length data
            len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStreamTxt.Close()

In this example we read bytes array chunk by chunk , but If you want to get all bytes value whithout using loop than use this code.

C# Example (Without Loop) :
    System.IO.FileStream objFileStreamTmp = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    byte[] objBufferTmp = new byte[objFileStreamTmp.Length];
    len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length);

    objFileStreamTmp.Close();

VB.net Example (Without Loop) :
        Dim objFileStreamTmp As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        Dim objBufferTmp As Byte() = New Byte(objFileStreamTmp.Length - 1) {}
        len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length)

        objFileStreamTmp.Close()

Note : The chunk by chunk means looping approach is very good when you open a large file. Because if you open a large file in one statement it may gives Memory related errors.

This is very useful .Net Tips which is use in day to day programming life.


Saturday, 16 June 2012

There is a very quick way in .Net to read the entire file and return a string of data.
We are using ReadAllText method of File class.
Here are sample example of this.
In this example we read the whole file in one statement and return it's string of data.
These examples are in both C# and VB.Net .

C# Example :
 // Read the entire file and returns a string of data
 string strData = System.IO.File.ReadAllText(MapPath("TextFile.txt"));

VB.net Example :
'' Read the entire file and returns a string of data
Dim strData As String = System.IO.File.ReadAllText(MapPath("TextFile.txt"))

This is very useful .Net Tips which is use in day to day programming life.


Thursday, 14 June 2012

There is a very quick way to open text file and appends data into that file.
There are two methods to appends text files AppendAllText and AppendAllLines.
These methods open a file. Appends data to the files , and then close the file. If file does not exist, These methods create the files , appends the data and close the file.

If you do not want append the data but you want overwrite the data of file you can also do this with the help of WriteAllText and WriteAllLines Methods.
These methods create the file and write data in file, If file is already exists than this will overwrite data.

Here are sample example of this.
In this example For append we are using AppendAllText method for directly append sample string.
and  AppendAllLines method to append IEnumerable of strings.
For write we are using WriteAllText method to write data in file and WriteAllLines method to write IEnumerable of strings.

C# Example :
    string strData = "This is sample string.";

    string[] lineNumbers = (from line in System.IO.File.ReadLines(MapPath("TextFile.txt"))
                            where line.Contains("sample")
                            select line).ToArray();

    // Appends the string of data to a file
    System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData);
    //Appends the IEnumerable of strings to a text file
    System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers);

    // Writes the string of data to a file
    System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData);

    // Writes an IEnumerable of strings to a text file
    System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers);

VB.net Example :
        Dim strData As String = "This is sample string."

        Dim lineNumbers As String() = (From line In System.IO.File.ReadLines(MapPath("TextFile.txt"))
                                      Where line.Contains("sample")
                                      Select line).ToArray()

        ' Appends the string of data to a file
        System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData)
        'Appends the IEnumerable of strings to a text file
        System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers)

        ' Writes the string of data to a file
        System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData)

        ' Writes an IEnumerable of strings to a text file
        System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers)

This is very useful .Net Tips which is use in day to day programming life.


Wednesday, 13 June 2012

.Net framework provide the System.IO.Compression.GZipStream or System.IO.Compression.DeflateStream to compress or decompress data.
Both GZipStream and DeflateStream classes allow you to use GZIP and Deflate compression algorithms to compress or decompress data.

Here are sample examples with GZipStream class.
The sample examples there are two methods one is CompressData and other is DCompressData.
In CompressData method we create a new file and uses the GZipStream class to write compressed file to it and close that file .
In DCompressData method we open that compressed file in read mode and decompressed the file and save.
In this sample you have to provide the file path which file you want to compress and also provide file path where the compressed file stored.
In this example we store both files in application root directory.

This examples are in both C# and VB.Net .

C# Example :
    protected void Page_Load(object sender, EventArgs e)
    {

        CompressData();
        DCompressData();
             
    }
    void CompressData()
    {
        // Create the compression stream.
        GZipStream objGZipOut = new GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress);
        
        int intBufferLength = 16 * 1024;
        byte[] objBuffer = new byte[intBufferLength];

        // Get File Stream Object
        System.IO.FileStream objFileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
        int len = 0;

        while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
        {
            // Write file Content 
            objGZipOut.Write(objBuffer, 0, len);

        }
        objFileStream.Close();
        objGZipOut.Close();
       
    }
    void DCompressData()
    {
        // Open the same gzip file to decompress
        GZipStream objGZipIn = new GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress);

        // Get stream reader of the gzip file.
        StreamReader objReader = new StreamReader(objGZipIn);
       
        byte[] buffer = new byte[16 * 1024];
        int len = 0;
        FileStream objFS = new FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
        while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            objFS.Write(buffer, 0, len);
        }
        objFS.Close();
        objReader.Close();
        objGZipIn.Close();
       
    }


VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CompressData()
        DCompressData()
    End Sub
    Private Sub CompressData()
        ' Create the compression stream.
        Dim objGZipOut As New GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress)

        Dim intBufferLength As Integer = 16 * 1  '1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        ' Get File Stream Object
        Dim objFileStream As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
        Dim len As Integer = 0
        len = objFileStream.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Write file Content 
            objGZipOut.Write(objBuffer, 0, len)
            len = objFileStream.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStream.Close()
        objGZipOut.Close()

    End Sub
    Private Sub DCompressData()
        ' Open the same gzip file to decompress
        Dim objGZipIn As New GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress)

        ' Get stream reader of the gzip file.
        Dim objReader As New StreamReader(objGZipIn)

        Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
        Dim len As Integer = 0
        Dim objFS As New FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
        len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        While len <> 0
            objFS.Write(buffer, 0, len)
            len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        End While
        
        objFS.Close()
        objReader.Close()
        objGZipIn.Close()

    End Sub

You can also provide other data like simple string to compress data , for that you have to use stream writer and use it's WriteLine method.

In this example we provide "TextFile.txt" text file. Size of this text file is 3 kb.
After the compressing new file "compressed_data.gzip" generated and it's size is 1 kb.

Output :

Before compression 



After compression 



Tuesday, 12 June 2012

You can also query the text file using LINQ .
Here are example for this.
In this example we can get specific lines which has matching word given by us.
After the LINQ query is executed you need to close file otherwise it gives error on next attempt to access of file.

C# Example :
string[] lineNumbers = (from line in
                        System.IO.File.ReadLines(MapPath(
                        where line.Contains("sample")
                        select line).ToArray();

System.IO.File.OpenText(MapPath("TextFile.txt")).Close();

VB.net Example :
Dim lineNumbers As String() = (From line In
                              System.IO.File.ReadLines(MapPath("TextFile.txt"))
                              Where line.Contains("sample")
                              Select line).ToArray()

System.IO.File.OpenText(MapPath("TextFile.txt")).Close()

Monday, 11 June 2012

You are able to get stream reader of a file and work on stream reader.
After getting Stream Reader and completing work on stream reader you have to close SteramReader using Close method. to avoid any file open errors.

Here are example for this.

C# Example :
System.IO.StreamReader objStreamReader = System.IO.File.OpenText(MapPath("TextFile.txt"));
objStreamReader.Close();

VB.net Example :
Dim objStreamReader As System.IO.StreamReader = System.IO.File.OpenText(MapPath("TextFile.txt"))
objStreamReader.Close()

Here in below image you can see that after FileStream Object is filled it's properties are set.

Output :

Friday, 8 June 2012

You can get the FileStream of a file by opening a file using File Class.
After get FileStream and completing work on file stream you have to close FileSteram using Close method. to avoid any file open errors.

Here are example for this.
C# Example :
System.IO.FileStream stream1 = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
stream1.Close();

VB.net Example :
Dim stream1 As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
stream1.Close()

Here in below image you can see that after FileStream Object is filled it's properties are set.

Output :

Wednesday, 9 May 2012

Using streams does have a couple problems that might encounter in certain scenarios.
  1. When you open a file using a stream, reading the file contents is done sequentially. This can be a problem if you are searching for a specific section of a very large file because you have to read the entire file from the beginning in order to locate the content.
  2. Opening a file using a stream can lock the file, preventing other applications or threads from reading or writing to the file.

.NET Framework includes the System.IO.MemoryMappedFiles namespace, which includes a number of classes that allow you to create memory-mapped files. Memory-mapped files can be useful when you encounter the limitations of the stream objects.

Memory-mapped files allow to create views that start in a random location over very large files, rather than reading the file from the beginning. Memory-mapped files also allow multiple processes to map to the same portion of a file without locking the file.

C# Example :
byte[] bytes = new byte[100];
using (System.IO.MemoryMappedFiles.MemoryMappedFile objMF = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile"))
{
    using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = objMF.CreateViewAccessor(100, 100))
    {
        accessor.ReadArray(0, bytes, 0, bytes.Length);
    }
}
Response.Write(ASCIIEncoding.Default.GetString(bytes));
This Example loads the TextFile.txt file into a MemoryMappedFile class using the static CreateFromFile method, which creates a named memory-mapped file. It then creates a MemoryMappedViewAccessor over the file using the MemoryMappedFiles CreateViewAccessor method. This method’s parameters allow  to specify an offset where the view accessor should start, the length of the view, and the access rights the view will have to the file.

The MemoryMappedFile class also allows to create memory-mapped files that are not associated with a physical file on disk, but are rather simply a named portion of memory. You can do this using the class’s static CreateNew method, which accepts a name and a length parameter.

VB.net Example :
Dim bytes As Byte() = New Byte(99) {}
    Using objMF As System.IO.MemoryMappedFiles.MemoryMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile")
        Using accessor As System.IO.MemoryMappedFiles.MemoryMappedViewAccessor = objMF.CreateViewAccessor(100, 100)
            accessor.ReadArray(0, bytes, 0, bytes.Length)
        End Using
    End Using
Response.Write(ASCIIEncoding.[Default].GetString(bytes))

Thursday, 12 April 2012

Some time you want to get directory information like sub directories  , last access time , last write time , Create new directory in to parent directory etc... programmatically using .Net.

You can get this information using "DirectoryInfo" class.
"DirectoryInfo" class available in System.IO Namespace.
There is one GetDirectories() method to get information about this.

Syntax :
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(string strDirectoryPath);

Here strDirectoryPath is relative path of directory for which you want to get information

Here are one example which get all directories information of given directory path
       System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("c:\\");
       //Here you can also specify path like "c:\\temp\\"   to get information of temp directory
        foreach (System.IO.DirectoryInfo objDirectory in directory.GetDirectories())
        {
            Response.Write("</br>Directory Name : " + objDirectory.Name);
            Response.Write("</br>Last Access Time : " + objDirectory.LastAccessTime);
            Response.Write("</br>Last Write Time : " + objDirectory.LastWriteTime);
                      
        }

Wednesday, 4 April 2012

You can get Drive info using DriveInfo class.
DriveInfo class available in System.IO Namespace.
You can get details like name, type, size, and status etc... of each drive.
There is one static method GetDrives() of DriveInfo Class.
Syntax :
    DriveInfo.GetDrives();

Here are sample Code for this :
        foreach (DriveInfo objDrive in DriveInfo.GetDrives())
        {
            Response.Write("</br>Drive Type : " + objDrive.Name);
            Response.Write("</br>Drive Type : " + objDrive.DriveType.ToString());
            Response.Write("</br>Available Free Space : " + objDrive.AvailableFreeSpace.ToString() + "(bytes)");
            Response.Write("</br>Drive Format : " + objDrive.DriveFormat);
            Response.Write("</br>Total Free Space : " + objDrive.TotalFreeSpace.ToString() + "(bytes)");
            Response.Write("</br>Total Size : " + objDrive.TotalSize.ToString() + "(bytes)");
            Response.Write("</br>Volume Label : " + objDrive.VolumeLabel);
            Response.Write("</br></br>");

        }