c#字符串to/from文本文档IO示例

2021-04-01 02:26

阅读:510

标签:adl   读取文本   console   TE   rgs   iot   字符串数组   OLE   writer   

写入文本文档

class Program
    {
        static void Main(String[] args)
        {
            //写入string数组,每个string一行
            string[] lines = { "first line", "second line ", "third line", "forth line" };
            System.IO.File.WriteAllLines(@"D:\IOTest\IOTest1.txt", lines);
            //写入一个字符串
            string text = "ahhhhhhhhhhhhhhhhhhhhhhhhhhh";
            System.IO.File.WriteAllText(@"D:\IOTest\IOTest2.txt", text);
            //StreamWriter类,以流的方式写入
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\IOTest\IOTest3.txt", true);
            foreach (var line in lines)
            {
                if (!line.Contains("second"))
                {
                    file.Write(line);
                    file.WriteLine(line);
                }
            }
            file.Flush();
            file.Close();
        }
    }

读取文本文件

class Program
    {
        static void Main(String[] args)
        {
            //读取为一个字符串
            string text = System.IO.File.ReadAllText(@"D:\iOTEST\IOTEST2.TXT");
            //读取为字符串数组,每行一个字符串
            string[] lines = System.IO.File.ReadAllLines(@"D:\IOTEST\IOTEST1.TXT");
            //StreamReader类,以流的方式读取
            System.IO.StreamReader sr = new System.IO.StreamReader(@"D:\iOTEST\IOTEST3.TXT");
            string str;
            while ((str = sr.ReadLine()) != null)
            {
                Console.WriteLine(str);
            }
            sr.Close();
        }
    }

 

c#字符串to/from文本文档IO示例

标签:adl   读取文本   console   TE   rgs   iot   字符串数组   OLE   writer   

原文地址:https://www.cnblogs.com/PanDaSong/p/9246529.html


评论


亲,登录后才可以留言!