Read and Write text files
Loadtocnode (2, 'summary ');
Read a text file
This section describes how to useStreamreader
Class to read text files. Write a text file (Example 1)
And write a text file (Example 2)
Each section describes how to useStreamwriter
Class to write text to a file.
Read text files
Loadtocnode (3, 'summary ');
Use the following codeStreamreader
Class to open, read, and close the text file. You can pass the path of a text file to automatically open the file.
Streamreader
Constructor.Readline
Method to read each line of text, and then increment the file pointer to the next line according to its reading.
Readline
When the method reaches the end of the file, it returns an empty reference.
- Create an example text file in notepad. To perform this operation, follow these steps:
- Paste the following text in Notepad:
hello world
- Save the file as sample.txt.
- Start Microsoft Visual Studio.
- InFile
PointNew
And then clickProject
.
- InProject Type
, ClickVisual C #
Project
And then clickTemplate
UnderConsole ApplicationNote:
In Visual Studio 2005 or visual
Maxcompute studio 2008, clickVisual C #
Project Type
, And then clickTemplate
UnderConsole Application
.
- Add the following code at the beginning of the class1.cs file:
using System.IO;
Note:
In the visual
Studio 2005 or Visual Studio 2008. The default file is program. CS.
- Add the following codeMain
Method:String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
Block.
- InDebugging
ClickStart
Compile and run the application. Press enter to close the console window. The console window is displayed in the sample.txt file.Hello world
Content in
Write a text file (Example 1)
Loadtocnode (3, 'summary ');
Use the following codeStreamwriter
Class, and close the text file.Streamreader
Class in a similar way, you can pass the path of the text file to automatically open the fileStreamwriter
Constructor.Writeline
Method To write a complete text line to a text file.
- Start Visual Studio.
- InFile
PointNew
And then clickProject
.
- InProject Type
, ClickVisual C #
Project
And then clickTemplate
UnderConsole Application
.Note:
In Visual Studio 2005 or visual
Maxcompute studio 2008, clickVisual C #
Project Type
, And then clickTemplate
UnderCLR console application
.
- Add the following code at the beginning of the class1.cs file:
using System.IO;
- Add the following codeMain
Method:try
{
//Pass the filepath and filename to the StreamWriter Constructor
StreamWriter sw = new StreamWriter("C:\\Test.txt");
//Write a line of text
sw.WriteLine("Hello World!!");
//Write a second line of text
sw.WriteLine("From the StreamWriter class");
//Close the file
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
Block.
- InDebugging
ClickStartCompile and run the application. This Code creates a file named test.txt too many characters before using C. open the file test.txt in a text editor (such as NotePad. Test.txt
Contains two lines of text:
Hello World!!
From the StreamWriter class
Write a text file (Example 2)
Loadtocnode (3, 'summary ');
Use the following codeStreamwriter
Class, and close the text file. Unlike the previous example, this code passes two additional parameters to the constructor.
The first parameter is the file path and file name. Second ParameterTrue
To open the append mode of the file. If you specify
False
, The content of the file will overwrite the code every time it is run. The third parameter is specified.Unicode
ToStreamwriter
Unicode files are encoded. You can also specify the following encoding method for the third parameter:
Write
Method andWriteline
The method is similar
Write
The method does not automatically embed a carriage return or line feed (CR/LF) character combination. This is useful when you want to write one character at a time.
- Start Visual Studio.
- InFile
PointNew
And then clickProject
.
- InProject Type
, ClickVisual C #
Project
And then clickTemplate
UnderConsole ApplicationNote:
In Visual Studio 2005 or visual
Maxcompute studio 2008, clickVisual C #
Project Type
, And then clickTemplate
UnderConsole Application
- Class1.cs
Add the following code at the beginning of the file:using System.IO;
using System.Text;
Note:
On Visual Studio 2005 or
Visual Studio 2008. The default file is program. CS.
- Add the following codeMain
Method:Int64 x;
try
{
//Open the File
StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
//Writeout the numbers 1 to 10 on the same line.
for(x=0; x < 10; x++)
{
sw.Write(x);
}
//close the file
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
- InDebugging
ClickStartCompile and run the application. This Code creates a file named test1.txt. open the file test1.txt in a text editor (such as NotePad.
Test1.txt contains a single line of text:
0123456789
Please refer to the following link for more information 〃
Loadtocnode (3, 'summary ');
- Read text files
//Read a Text File
using System;
using System.IO;
namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
Block.
- Write a text file (version 1)
//Write a text file - Version-1
using System;
using System.IO;
namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
//Pass the filepath and filename to the StreamWriter Constructor
StreamWriter sw = new StreamWriter("C:\\Test.txt");
//Write a line of text
sw.WriteLine("Hello World!!");
//Write a second line of text
sw.WriteLine("From the StreamWriter class");
//Close the file
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
Block.
- Write a text file (version 2)
//Write a text file - Version 2
using System;
using System.IO;
using System.Text;
namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Int64 x;
try
{
//Open the File
StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
//Writeout the numbers 1 to 10 on the same line.
for(x=0; x < 10; x++)
{
sw.Write(x);
}
//close the file
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
Troubleshooting
Loadtocnode (3, 'summary ');
It is a good programming habit for all file operations.Try-catch-finally
Block to handle errors and abnormal code.
Specifically, you may want to release the handle of the file in the last block so that the file is not locked indefinitely. Some possible errors include a file that does not exist or is in use.
For more information, visit the following Microsoft Developer Network (msdn) Website:
Streamreader class
Http://msdn2.microsoft.com/en-us/library/system.io.streamreader (vs.71). aspx
(Http://msdn2.microsoft.com/en-us/library/system.io.streamreader (vs.71). aspixel)
]