Tuesday, August 04, 2009

C# File.WriteAllText, File.ReadAllText & File.WriteAllLines

Most of the times as developers we have to work with text files, as it’s a very simple way to store some data. There are very valuable methods available in File class that we are not using most often.

Look at the following example which writes a formatted string to a text file with new lines.
This is more readable than WriteLine() method. If you use WriteLine() Method then you will have to write line by line most probably you may have to use a loop.

protected void btnTextManipulation_Click(objectsender, EventArgs e)
//gets the file path
stringfilePath = Server.MapPath("Files/test.txt");
StringBuilder content = new StringBuilder();

//note the end of this line i.e \r\n this says enter a new line
content.Append("This is the first line. \r\n");
content.Append("This is the secont line. \r\n");

//Environment.NewLine this says enter a new line too
content.Append("This is the last line."+ Environment.NewLine);

//Writes to test.txt
WriteText(filePath, content.ToString());

//reads from test.txt and asssing to a variable
stringreadTxt = ReadText(filePath);

filePath = Server.MapPath("Files/test2.txt");
//Writes to test2.txt
WriteText(filePath, readTxt);

public void WriteText(stringpath, stringcontent)
//this file method writes all test you pass
File.WriteAllText(path, content);

public string ReadText(stringpath)
//this file method reads whole content of the text file.

I will show another example which writes array items in new lines.In the following example WriteAllines() method writesall the items in an array as a new line. With using WriteAllLines() method you can avoid a loop, hich needs to loop through the array and WriteLine to the text file.

protected void btnTextManipulation_Click1(object sender, EventArgs e)
//get the file path
string filePath = Server.MapPath("Files/test.txt");
//declare and assign a string array
string[] content = { "This is the first line.", "his is the secont line.", "This is the last line." };
WriteArrayText(filePath, content);

public void WriteArrayText(string path, string[] content)
//this file method writes all test you pass
File.WriteAllLines(path, content);


My Achievements

Member of

Blog Archive