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.
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 codeFile.WriteAllText(fileNameWithPath, data); // reading content from a textfile with single line of codestring 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 />");
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
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
" + strb.ToString() + "
"); }
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.
'Framework' 카테고리의 다른 글
LINQ 자료 (2) | 2009.10.09 |
---|---|
C# Collection Classes (부제:List 와 ArrayList 의 차이 ) (0) | 2009.10.06 |
[펌]Mircrosoft Office 2007 Groove 사용 방법 (0) | 2009.09.02 |
XML 특수문자 처리 (0) | 2009.08.11 |
.NET Naming Rule Guidelines (0) | 2009.07.02 |