Saturday, 18 November 2006

Various ways of file read/write in .net framework

I have summarized various ways of file IO in .net framework. There are many ways of doing same thing in file IO.


string path = @"C:\Temp\Test.txt";
// 1. Using System.IO.File.ReadAllLines to read lines of file content into an array of strings
string[] lines = File.ReadAllLines(path);

// 2. Using System.IO.File.ReadAllText to read the whole content of a file to a string
string s = File.ReadAllText(path);

// 3. Using StreamReader, File and FileStream calsses
FileStream theFile = File.Open(path, FileMode.Open, FileAccess.Read);
StreamReader rdr = new StreamReader(theFile);
string s = rdr.ReadToEnd();

// 4. Using StreamReader class only
StreamReader rdr = new StreamReader(path);
string s = rdr.ReadToEnd();

// 5. Using StreamReader and File class
StreamReader rdr = File.OpenText(path);
string s = rdr.ReadToEnd();

// 6. Using MemoryStream class to write to file to improve performance
MemoryStream memStrm = new MemoryStream();
StreamWriter writer = new StreamWriter(memStrm);
writer.WriteLine("hello");
writer.Flush();

// write content in MemoryStream to file stream
FileStream theFile = File.Create(path);
memStrm.WriteTo(theFile);

// 7. Using BufferedStream to improve performance.
FileStream file = File.Create(path);
BufferedStream buffered = new BufferedStream(file);
StreamWriter writer = new StreamWriter(buffered);
writer.WriteLine("hello");
writer.Close();

// 8. Using GZipStream to compress data. The source file is a normal file. The destination file is compressed.
FileStream source = File.Open(inFileName);
FileStream dest = File.Open(outFileName);

GZipStream comStrm = new GZipStream(dest, CompressionMode.Compress);

int theByte = source.ReadByte();
while (theByte != -1)
{
comStrm.WriteByte((byte)theByte);
int theByte = source.ReadByte();
}

// 9. Using GZipStream to decompress data. The source file is a compressed file. The destination file is normal.
FileStream source = File.Open(inFileName);
FileStream dest = File.Open(outFileName);

GZipStream comStrm = new GZipStream(dest, CompressionMode.Decompress);

int theByte = source.ReadByte();
while (theByte != -1)
{
comStrm.WriteByte((byte)theByte);
int theByte = source.ReadByte();
}

// 10. Using FileInfo class
FileInfo fileInfo = new FileInfo(path);
FileStream stream = fileInfo.Open(FileMode.Open, FileAccess.Read);

No comments: