zoukankan      html  css  js  c++  java
  • C#基础 字符串读取/写入文本文件 代码示例

    写入文本文件:

     1     class Program
     2     {
     3         static void Main(String[] args)
     4         {
     5             //写入string数组,每个string一行
     6             string[] lines = { "first line", "second line ", "third line", "forth line" };
     7             System.IO.File.WriteAllLines(@"D:IOTestIOTest1.txt", lines);
     8             //写入一个字符串
     9             string text = "ahhhhhhhhhhhhhhhhhhhhhhhhhhh";
    10             System.IO.File.WriteAllText(@"D:IOTestIOTest2.txt", text);
    11             //StreamWriter类,以流的方式写入
    12             System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:IOTestIOTest3.txt", true);
    13             foreach (var line in lines)
    14             {
    15                 if (!line.Contains("second"))
    16                 {
    17                     file.Write(line);
    18                     file.WriteLine(line);
    19                 }
    20             }
    21             file.Flush();
    22             file.Close();
    23         }
    24     }

    读取文本文件:

     1     class Program
     2     {
     3         static void Main(String[] args)
     4         {
     5             //读取为一个字符串
     6             string text = System.IO.File.ReadAllText(@"D:iOTESTIOTEST2.TXT");
     7             //读取为字符串数组,每行一个字符串
     8             string[] lines = System.IO.File.ReadAllLines(@"D:IOTESTIOTEST1.TXT");
     9             //StreamReader类,以流的方式读取
    10             System.IO.StreamReader sr = new System.IO.StreamReader(@"D:iOTESTIOTEST3.TXT");
    11             string str;
    12             while ((str = sr.ReadLine()) != null)
    13             {
    14                 Console.WriteLine(str);
    15             }
    16             sr.Close();
    17         }
    18     }
  • 相关阅读:
    测试方法与步骤
    团队项目需求分析
    第一次个人作业
    3种shell自动交互的方法
    mysql用户管理
    build web application with golang
    安卓中的LINUX内核
    结对项目小结
    关于aria2-yaaw下载软件
    软工结对项目预览
  • 原文地址:https://www.cnblogs.com/vsSure/p/7868623.html
Copyright © 2011-2022 走看看