当前位置:首页 > 如何在c#中操作txt文本文件

如何在c#中操作txt文本文件

点击次数:1302  更新日期:2010-12-27
\n

 

\n

// C#文本文件操作
\n//如何向现有文件中添加文本

\n

 

\n

using System;using System.IO;
\nclass Test {
\npublic static void Main() {
\n// Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. using
\n(StreamWriter sw = new StreamWriter(“TestFile.txt”))
\n{// Add some text to the file.
\nsw.Write(“This is the “);
\nsw.WriteLine(“header for the file.”);
\nsw.WriteLine(“——————-”);
\n// Arbitrary objects can also be written to the file.
\nsw.Write(“The date is: “);
\nsw.WriteLine(DateTime.Now);
\n}
\n}
\n}

\n

 

\n

//如何创建一个新文本文件并向其中写入一个字符串。WriteAllText方法可提供类似的功能。
\nusing System;
\nusing System.IO;
\npublic class TextToFile {
\nprivate const string FILE_NAME = “MyFile.txt”;
\npublic static void Main(String[] args)
\n{
\nif (File.Exists(FILE_NAME))
\n{
\nConsole.WriteLine(“{0} already exists.”, FILE_NAME);
\nreturn;
\n}
\nusing (StreamWriter sw = File.CreateText(FILE_NAME))
\n{
\nsw.WriteLine (“This is my file.”);
\nsw.WriteLine (“I can write ints{0} or floats {1}, and so on.”, 1, 4.2);
\nsw.Close();
\n}
\n}
\n}

\n

\n

//如何从文本文件中读取文本
\nusing System;using System.IO;
\nclass Test {
\npublic static void Main()
\n{
\ntry{
\n// Create an instance of StreamReader to read from a file.
\n// The using statement also closes the StreamReader.
\nusing (StreamReader sr = new StreamReader(“TestFile.txt”))
\n{String line;
\n// Read and display lines from the file until the end of
\n// the file is reached.
\nwhile ((line = sr.ReadLine()) != null) {
\nConsole.WriteLine(line);
\n}
\n}
\n}
\ncatch (Exception e)
\n{
\n// Let the user know what went wrong.
\nConsole.WriteLine(“The file could not be read:”);
\nConsole.WriteLine(e.Message);
\n}
\n}
\n}
\n//在检测到文件结尾时向您发出通知。通过使用 ReadAll 或 ReadAllText 方法也可以实现此功能。
\nusing System;using System.IO;
\npublic class TextFromFile {
\nprivate const string FILE_NAME= “MyFile.txt”;
\npublic static void Main(String[] args)
\n{
\nif (!File.Exists(FILE_NAME))
\n{
\nConsole.WriteLine(“{0} does not exist.”, FILE_NAME);
\nreturn;
\n}
\nusing (StreamReader sr = File.OpenText(FILE_NAME))
\n{
\nString input;
\nwhile ((input=sr.ReadLine())!=null){
\nConsole.WriteLine(input);
\n}
\nConsole.WriteLine (“The end of the stream has been reached.”);
\nsr.Close();
\n}
\n}
\n

\n

来源:csdn

\n

 

\n