This article is a mirror article of machine translation, please click here to jump to the original article.

View: 20274|Reply: 0

[Source] C# writes and reads out text files

[Copy link]
Posted on 10/10/2015 10:03:21 AM | | |

  1. class WriteTextFile
  2.     {
  3.         static void Main()
  4.         {
  5.             //如果文件不存在,则创建;存在则覆盖
  6.             //该方法写入字符数组换行显示
  7.             string[] lines = { "first line", "second line", "third line","第四行" };
  8.             System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);

  9.             //如果文件不存在,则创建;存在则覆盖
  10.             string strTest = "该例子测试一个字符串写入文本文件。";
  11.             System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);

  12.             //在将文本写入文件前,处理文本行
  13.             //StreamWriter一个参数默认覆盖
  14.             //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾
  15.             using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt",true))
  16.             {
  17.                 foreach (string line in lines)
  18.                 {
  19.                     if (!line.Contains("second"))
  20.                     {
  21.                         file.Write(line);//直接追加文件末尾,不换行
  22.                         file.WriteLine(line);// 直接追加文件末尾,换行   
  23.                     }
  24.                 }
  25.             }
  26.         }
  27.     }
Copy code






Previous:ASP.NET a collection of methods to get the root directory
Next:Baidu Cloud accelerates attention to email address obfuscation/WAF
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com