C#写入文件的几种方式
1 1. FileStream.Write 2 3 string filePath = Directory.GetCurrentDirectory() + "\\" + Process.GetCurrentProcess().ProcessName + ".txt"; 4 if (File.Exists(filePath)) 5 File.Delete(filePath); 6 7 FileStream fs = new FileStream(filePath, FileMode.Create); 8 //获得字节数组 9 10 string xyPointer = string.Format("X: {0}, Y: {1}", this.Location.X.ToString(), this.Location.Y.ToString()); 11 string highWidth = string.Format("\nW: {0}, H: {1}", this.Width.ToString(), this.Height.ToString()); 12 byte[] data = System.Text.Encoding.Default.GetBytes(xyPointer + highWidth); 13 //开始写入 14 fs.Write(data, 0, data.Length); 15 //清空缓冲区、关闭流 16 fs.Flush(); 17 fs.Close(); 18 19 2. File.WriteAllLines 20 21 //如果文件不存在,则创建;存在则覆盖 22 //该方法写入字符数组换行显示 23 string[] lines = { "first line", "second line", "third line", "第四行" }; 24 System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8); 25 26 3. File.WriteAllText 27 28 //如果文件不存在,则创建;存在则覆盖 29 string strTest = "该例子测试一个字符串写入文本文件。"; 30 System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8); 31 32 4. StreamWriter.Write 33 34 //在将文本写入文件前,处理文本行 35 //StreamWriter一个参数默认覆盖 36 //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾 37 using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt", true)) 38 { 39 foreach (string line in lines) 40 { 41 if (!line.Contains("second")) 42 { 43 file.Write(line);//直接追加文件末尾,不换行 44 file.WriteLine(line);// 直接追加文件末尾,换行 45 } 46 } 47 }