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

写入文本文档

class Program
    {
        static void Main(String[] args)
        {
            //写入string数组,每个string一行
            string[] lines = { "first line", "second line ", "third line", "forth line" };
            System.IO.File.WriteAllLines(@"D:IOTestIOTest1.txt", lines);
            //写入一个字符串
            string text = "ahhhhhhhhhhhhhhhhhhhhhhhhhhh";
            System.IO.File.WriteAllText(@"D:IOTestIOTest2.txt", text);
            //StreamWriter类,以流的方式写入
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:IOTestIOTest3.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:iOTESTIOTEST2.TXT");
            //读取为字符串数组,每行一个字符串
            string[] lines = System.IO.File.ReadAllLines(@"D:IOTESTIOTEST1.TXT");
            //StreamReader类,以流的方式读取
            System.IO.StreamReader sr = new System.IO.StreamReader(@"D:iOTESTIOTEST3.TXT");
            string str;
            while ((str = sr.ReadLine()) != null)
            {
                Console.WriteLine(str);
            }
            sr.Close();
        }
    }
原文地址:https://www.cnblogs.com/PanDaSong/p/9246529.html