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     }
  • 相关阅读:
    常见常用的CSS
    Js删除数组函数
    使用CSS让多出来的字变为省略号
    CSS缩写的样式
    mac下安装nginx
    ubuntu下程序员常用命令大全
    vue.js实现瀑布流之vue-waterfall-easy
    vue.js常见的报错信息及其解决方法的记录
    laravel5.4生成验证码
    java算法之超级丑数
  • 原文地址:https://www.cnblogs.com/vsSure/p/7868623.html
Copyright © 2011-2022 走看看