c# |指定地址创建文件,文本的读写
参考:https://www.runoob.com/csharp/csharp-file-io.html
1. 在D:\Sample文件目录下创建sample.txt文本文件,并向其中写入字符数据;若文件已存在,则覆盖原本的内容写入指定字符数据,若文件不存在,则创建新的文件写入字符数据
using System;using System.IO;using System.Text;
string path = @"D:\Sample\sample.txt";//设定指定地址D:\Sample
// This text is added only once to the file.
if (File.Exists(path))
{
string CreateTxt = "Please close the window" + Environment.NewLine;//Environment.NewLine是Environment类的换行的意思
File.WriteAllText(path, CreateTxt);
}
//如果文件不存在,则创建新的文件
else
{
string AppendText = "Please open the window" + Environment.NewLine;
File.AppendAllText(path, AppendText);
}
//打开文件内容读取到运行窗口
Console.WriteLine(File.ReadAllText(path));
Console.ReadLine();
WriteAllText和AppendAllText的区别