C#写入文件的几种方式

 1. FileStream.Write

string filePath = Directory.GetCurrentDirectory() + "\\" + Process.GetCurrentProcess().ProcessName + ".txt";
if (File.Exists(filePath))
  File.Delete(filePath);

FileStream fs = new FileStream(filePath, FileMode.Create);
//获得字节数组

string xyPointer = string.Format("X: {0}, Y: {1}", this.Location.X.ToString(), this.Location.Y.ToString());
string highWidth = string.Format("\nW: {0}, H: {1}", this.Width.ToString(), this.Height.ToString());
byte[] data = System.Text.Encoding.Default.GetBytes(xyPointer + highWidth);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();

2. File.WriteAllLines

//如果文件不存在,则创建;存在则覆盖
//该方法写入字符数组换行显示
string[] lines = { "first line", "second line", "third line", "第四行" };
System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);

3. File.WriteAllText

//如果文件不存在,则创建;存在则覆盖
string strTest = "该例子测试一个字符串写入文本文件。";
System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);

4. StreamWriter.Write

//在将文本写入文件前,处理文本行
//StreamWriter一个参数默认覆盖
//StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt", true))
{
  foreach (string line in lines)
  {
    if (!line.Contains("second"))
    {
      file.Write(line);//直接追加文件末尾,不换行
      file.WriteLine(line);// 直接追加文件末尾,换行
    }
  }
}

posted @ 2015-11-23 19:25  Researcher  阅读(85501)  评论(0编辑  收藏  举报