Text file is the most convenient way to store any kind of data temporarily and very frequently used these days in any kinds of applications. This article shows different ways of reading and writing text files data in .NET.
Introduction
Text files are easy way to store data in either comma separated values or separated by new line. While working with many application usually we come across situations where we need to read and write data from / into text files. This article describes different approach of reading and writing data into the text files.
Essentials
In order to work with reading and writing data from / into text file, you will have to use System.IO namespace. You need to specify the path of the file to read from and write data into as Physical path on your hard driver. If you know the physical path of your file you want to read or write, you can specify as follows
string fileNameWithPath = @"E:\Csharp\temp\withsinglelinecode.txt";
If you do not know or not sure the path of the file from the drive or you want to create the text file in your applications sub folders, you can get the physical file path by using Server.MapPath method and passing the location of the file from your root directory of the application.
string fileNameWithPath = Server.MapPath("temp/withsinglelinecode1.txt");
In order to create a new line into the text file, you can use System.Environment.NewLine or "\r\n", to place a tab space you can use "\t". Reading data from text file and showing on the web page, will not automatically convert \r\n to new line, you will have to replace these characters with the <br /> as shown below.
litText.Text = contents.Replace("\r\n", "<br />");
Here litText is the Literal control I have placed in my .aspx page to show the contents of the file.
Get solutions of .NET problems with video explanations, .pdf and source code in .NET How to's.
Reading and Writing with Single line of code
To simply write and read all contents of any any text file, you can use following one line code.
C# Code
string data = "This is the first line . \r\n" +
"This is the second line. next two line space \r\n\r\n" +
"\t This comes after a tab space";
// writing content into a text file with a single line of code
File.WriteAllText(fileNameWithPath, data);
// reading content from a textfile with single line of code
string contents = File.ReadAllText(fileNameWithPath);
// Format the data with new line so that on the web page it appears in the new line
litText.Text = contents.Replace("\r\n", "<br />");
VB.NET Code
1: ' SINGLE LINE OF CODE
2: ' =========================
3: ' writing content into a text file with a single line of code
4: File.WriteAllText(fileNameWithPath, data)
5:
6: ' reading content from a textfile with single line of code
7: Dim contents As String = File.ReadAllText(fileNameWithPath)
8: litText.Text = contents
9: litText.Text = contents.Replace(vbCr & vbLf, "<br />")
In the above code snippet, File.WriteAllText method accepts following parameters
- fileNameWithPath - physical location of the file with its name
- data - contents to write into the text file
File.ReadAllText method accepts following parameters
- fileNameWithPath - physical location of the file with its name
In the remaining lines, I have replaced the new line characters with the "<br />" so that it appears as next line in my web page.
Appending contents into a File and Reading data one by one
C# Code
// Append data into the text file
using (StreamWriter writer = File.AppendText(fileNameWithPath))
{// writer.Write method will simply append the contents into the text
// file without creating a new line
writer.Write("NEW LINE ADDED without Creating a line line. ");
writer.Write("This line will not appear into new line. ");
// writer.WriteLine method append the contents into the text file
// and add a new line so that next appended contents appear in new line
writer.WriteLine("Appended into above line but next appended contents will appear into a new line. ");
writer.Write("This should appear in the next line. ");
}
// Read data from text file
using (StreamReader reader = File.OpenText(fileNameWithPath))
{
// reads a single line of contents
contents = reader.ReadLine();
// reads complete contents of the the file
contents += reader.ReadToEnd();
}
litText.Text = contents;
VB.NET Code
1:
2:' Append data into text file
3: Using writer As StreamWriter = File.AppendText(fileNameWithPath)
4: ' writer.Write method will simply append the contents into the text
5: ' file without creating a new line
6: writer.Write("NEW LINE ADDED without Creating a line line. ")
7: writer.Write("This line will not appear into new line. ")
8:
9: ' writer.WriteLine method append the contents into the text file
10: ' and add a new line so that next appended contents appear in new line
11: writer.WriteLine("Appended into above line but next appended contents will appear into a new line. ")
12: writer.Write("This should appear in the next line. ")
13: End Using
14: ' Reading data from text file
15: Using reader As StreamReader = File.OpenText(fileNameWithPath)
16: ' reads a single line of contents
17: contents = reader.ReadLine()
18:
19: ' reads complete contents of the the file
20: contents += reader.ReadToEnd()
21: End Using
22:
23: litText.Text = contents
In the above code snippets, I am using StreamWriter to append the contents into the file. File.AppendText method accepts physical location of the file with its name and returns StreamWriter, that can be used to append contents into the text file. This can be done using Write method or WriteLine method.
- writer.Write() - method accepts contents to append and simply append the contents at the end of the file.
- writer.WriteLine() - method accepts contents to append and add a new line after appending contents so that next appended contents appears in the new line.
Reading and Writing using FileStream
C# Code
// using File Stream
fileNameWithPath = Server.MapPath("temp/filestream.txt");
// writing contents using FileStream
using (FileStream stream = File.Open(fileNameWithPath, FileMode.OpenOrCreate))
{
// writing data
byte[] info = new UTF8Encoding(true).GetBytes(data);
stream.Write(info, 0, info.Length);
}
// Reading contents using FileStream
using (FileStream stream = File.OpenRead(fileNameWithPath))
{
// reading data
StringBuilder strb = new StringBuilder();
byte[] b = new byte[stream.Length];
UTF8Encoding temp = new UTF8Encoding(true);
while (stream.Read(b, 0, b.Length) > 0)
{
strb.Append(temp.GetString(b));
}
// write the contents of the file now
Response.Write("Using FileStream <hr />" + strb.ToString() + "<hr />");
}
VB.NET Code
1:
2: ' using File Stream
3: fileNameWithPath = Server.MapPath("temp/filestream.txt")
4: ' writing contents using FileStream
5: Using stream As FileStream = File.Open(fileNameWithPath, FileMode.OpenOrCreate)
6: ' writing data
7: Dim info As Byte() = New UTF8Encoding(True).GetBytes(data)
8: stream.Write(info, 0, info.Length)
9: End Using
10:
11: ' Reading contents using FileStream
12: Using stream As FileStream = File.OpenRead(fileNameWithPath)
13: ' reading data
14: Dim strb As New StringBuilder()
15: Dim b As Byte() = New Byte(stream.Length) {}
16: Dim temp As New UTF8Encoding(True)
17: While stream.Read(b, 0, b.Length) > 0
18: strb.Append(temp.GetString(b))
19: End While
20: Response.Write("Using FileStream <hr />" + strb.ToString() + "<hr />")
21: End Using
FileStream object gives you extra control over how you want to read or write data from / into a file. This also let you specify the mode of the file to access like in Append mode, or Create mode or only Read mode. Also you can specify Type of access you want to have as third parameter of the File.Open() method.
FileStream buffers input and output for better performance. In order to use FileStream for reading and writing, you will need to use System.Text namespace as encoding related objects like UTF8Encoding contains in this namespace.
For detailed explanations FileStream, please visit MSDN.
Conclusion
In this article, we saw different ways of reading and writing files from / into text file. Hope this article on reading and writing contents from / into text file will helpful for the reders. If you liked this article, please
subscribe for subsequent articles alert in your email directly. Thanks for reading. Happy coding !