创建文件并写入内容

StreamWriter sw = new StreamWriter(url, “false 覆盖,true 追加”, Encoding.UTF8);
sw.Write(“内容”);
sw.Close();

读取文件内容

FileInfo info = new FileInfo("路径");
            FileStream fs = new FileStream(pash, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] b = new byte[info.Length];
            fs.Read(b, 0,b.Length);
            UTF8Encoding utf = new UTF8Encoding();
            string st = utf.GetString(b);
            fs.Close();
            //st 文本内容

 FileStream 个方法中也有创建、写入、读取等方法。

补充:

是否存在,没有新建

if (!File.Exists(file))
            {
                FileStream fs1 = new FileStream(file, FileMode.Create, FileAccess.Write);//创建写入文件               
                fs1.Close();
            }     

一行一行的读取

string text = System.IO.File.ReadAllText(file);
            Console.WriteLine(text);
            //从头到尾以流的方式读出文本文件
            //该方法会一行一行读出文本
            using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
            {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    Console.WriteLine(str);
                }
            }
            Console.Read();          

 清空

System.IO.File.WriteAllText(file, string.Empty);

 

相关文章:

  • 2022-01-18
  • 2022-12-23
  • 2021-05-13
  • 2021-10-05
  • 2021-10-07
  • 2021-10-22
  • 2022-02-03
猜你喜欢
  • 2021-07-16
  • 2021-11-25
  • 2021-05-29
  • 2021-10-11
  • 2021-07-26
  • 2021-11-26
相关资源
相似解决方案