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", "forth line" };
System.IO.File.WriteAllLines(@"路径\文件名", lines, Encoding.UTF8);

3. File.WriteAllText

//如果文件不存在,则创建;存在则覆盖
string strTest = "abcdefg";
System.IO.File.WriteAllText(@"路径\文件名", strTest, Encoding.UTF8);

4. StreamWriter.Write

using (StreamWriter sw = new StreamWriter(@"路径\文件名"))

                {
                    for (int i = 0; i < lines.Length; i++)
                   {
                        sw.WriteLine(lines[i]);
                    }
                    sw.Close();
                }

猜你喜欢

转载自blog.csdn.net/lwjzjw/article/details/80761061