C#如何写入字符串数据到txt文本文件,并从txt文件中读取文本数据呢?只需要使用System.IO.File对象里面提供的静态方法即可实现这些功能,下面先来看一下C#写入txt文本数据的示例,如下有4中方式实现:
class WriteTextFile { static void Main() { //写入字符串数组到txt,不需要自己Flush() 或 Close() string[] lines = { "First line", "Second line", "Third line" }; System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines); // 写入字符串到txt,不需要自己Flush() 或 Close() string text = "我是要写入的文本数据,哈哈"; System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text); // 通过FileStream对象写入数组里面的字符串,需要手动WriteLine换行 // using子句会自动Flush() 或 Close() using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt")) { foreach (string line in lines) { // 如果不包含second字符串则写入 if (!line.Contains("Second")) { file.WriteLine(line); } } } //FileStream对象写入字符串数据到txt using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true)) { file.WriteLine("Fourth line"); } } }
那么C#如何从txt文本中读取数据呢?请看下面的使用示例:
class ReadFromFile { static void Main() { // Example #1,读取所有文本 string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt"); // 输出 System.Console.WriteLine("Contents of WriteText.txt = {0}", text); // Example #2 读取每一行数据到字符串数组中 string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt"); // 输出数组数据 System.Console.WriteLine("WriteLines2.txt= "); foreach (string line in lines) { Console.WriteLine("\t" + line); } Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } }