Sunday, December 28, 2008

File Handling In C#

File is a static class.

The table shows the most useful File methods we can use.

Method name

Use

File.ReadAllBytes

Useful for files not stored as plain text.
See example near the bottom.

File.ReadAllLines

Microsoft: "Opens a file, reads all lines of the file with the specified encoding, and closes the file."
See the benchmark below.

File.ReadAllText

Returns the contents of the text file at the specified path as a string.
See the benchmark below.

File.WriteAllBytes

Not covered here.
It should be used in conjunction with File.ReadAllBytes.

File.WriteAllLines

Stores a string array in the specified file, overwriting the contents.

File.WriteAllText

Writes the contents string to a text file.

File.AppendAllText

Use to append the contents string to the file at path.
Microsoft: "Appends the specified string to the file, creating the file if it doesn't already exist."

File.AppendText

Not covered here.
You must use standard StreamWriter code.




File.ReadAllBytes.

we can use it to cache an image in memory for performance.It will increase the performance too.


static class ImageCache
{
static byte[] _logoBytes;
public static byte[] Logo
{
get
{
//
// Returns logo image bytes.
//


if (_logoBytes == null)
{
_logoBytes = File.ReadAllBytes("Logo.png");
}
return _logoBytes;
}
}
}


File.ReadAllLines

The following code reads in each line in the file "file.txt" into an array.


// Read in every line in specified file.
// This will store all lines in an array in memory,
// which you may not want or need.
//

string[] lines = File.ReadAllLines("file.txt");
foreach (string line in lines)
{
//
// Do something with line
//

if (line.Length > 80)
{
// Example code (disregard).
}
}


StreamReader ReadLine

This method is not part of the File static class, but it is in the System.IO
namespace. I provide it here as a comparison to the File.ReadAllLines method.
Here is some data about how the two methods to read lines perform on different
sized files.



// Read in every line in the file.
//
// Note how |using| wraps the StreamReader.
// The condition in |while| is also very important to get right.
//

using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//
// Do something with line just for example.
//

string[] parts = line.Split(',');
}
}


File.ReadAllText

It is used to rad the text from our data file.


void Example()
{
//
// A.
// Read in file with File class.
//
string text1 = File.ReadAllText("file.txt");

//
// B.
// Read in file text with helper method and StreamReader.
// 40% faster!
//
string text2 = ReadFileString("file.txt");
}

static string ReadFileString(string path)
{
//
// Use StreamReader to consume the entire text file.
//
using (StreamReader reader = new StreamReader(path))
{
return reader.ReadToEnd();
}
}

StreamReader helper. In some projects, it would be worthwhile to use the above ReadFileString custom static method.


File.ReadAllLines

List and ArrayList are extremely useful data structures for us programmers, as they allow us to rapidly expand (or shrink) large (or small) 'collections' of objects. Here we see how we can use LINQ to get a List of lines from a file in one line.



//
// Read in all lines in the file,
// and then convert to List with LINQ.
//
List fileLines = File.ReadAllLines("file.txt").ToList();



File.ReadAllLines

Do you need to count the lines in a file? Every developer has had this requirement at some time. Are there 10 or 10,000 lines in the web server log file? We don't need to write ten lines of code to do this. Simply reference the Length property.


// Another method of counting lines in a file.
// This is NOT the most efficient way, and it
// counts empty lines.
//
int lineCount = File.ReadAllLines("file.txt").Length;

See if a line exists in a file

Does a line containing a specific string exist in the file? Maybe you want to see if a name or location exists in a line in the file. Here again we can harness the power of LINQ to find any matching line.


// One way to see if a certain string is a line
// in the specified file. Uses LINQ to count elements
// (matching lines), and then sets |exists| to true
// if more than 0 matches were found.
//
bool exists = (from line in File.ReadAllLines("file.txt")
where line == "Some line match"
select line).Count() > 0;



File.WriteAllLines

When you are done with your in-memory processing, you often need to write the data to disk. Fortunately, the File class offers an excellent WriteAllLines method. It receives the file path and then the array to write. This will replace all the file contents.


// Write a string array to a file.

string[] stringArray = new string[]
{
"cat",
"dog",
"arrow"
};
File.WriteAllLines("file.txt", stringArray);
// File contains:
// cat
// dog
// arrow


Append text to files

The previous example will replace the file's contents, but for a log file or error listing, we must append to the file. (Sure, we could read in the file, append to that in memory, and then write it out completely again. But that's slow.)


// Append text to a file.
// This method will create a new file if one isn't already there.
// No newlines will be automatically added.
//
File.AppendAllText("file.txt", "test");
// File contains:
// test
File.AppendAllText("file.txt", "more");
// File contains:
// testmore
So friends File handling is quite easy in C#.

2 comments:

  1. This information is really useful. Gud Work!!

    I want to know that would these codes work for xml file also? Actually I ve requirement as the application would read the existing xml file, search for particular attribute (that has been generated by application as in form of random number) and again generate the random number not same as the existing attributes.

    ReplyDelete
  2. Hi Jaya,
    I have explained how to read and write data from XML in my post
    "Read XML in C#.net"

    Hope this will solve your problem.

    ReplyDelete