• 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("
    W: {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:	estDir	est.txt", lines, Encoding.UTF8);
    25 
    26 3. File.WriteAllText
    27 
    28 //如果文件不存在,则创建;存在则覆盖
    29 string strTest = "该例子测试一个字符串写入文本文件。";
    30 System.IO.File.WriteAllText(@"C:	estDir	est1.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:	estDir	est2.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 }
  • 相关阅读:
    nodejs学习笔记
    php操作mysql数据库
    HTML5 新特性总结
    万恶的浏览器兼容问题
    图标字体使用方法
    托管代码
    进程间通信,把字符串指针作为参数通过SendMessage传递给另一个进程,不起作用
    利用自定义消息处理函数的WPARAM或LPARAM参数传递指针
    自定义消息中如果需要定义WPARAM和LPARAM,该怎么使用和分配?
    提高VS2010运行速度的技巧+关闭拼写检查
  • 原文地址:https://www.cnblogs.com/hushaojun/p/10601022.html
Copyright © 2020-2023  润新知