在C#中,有很多不同的方法可以读写文件(文本文件,而非二进制文件)。
我只需要一种简单且使用最少量代码的方法,因为在我的项目中我将经常处理文件。我只需要处理 string
类型,因为我只需要读写 string
。
private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}
string filePath = @"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);
简单地说:
String inputText = "Hello World!";
File.WriteAllText("yourfile.ext",inputText); //writing
var outputText = File.ReadAllText("yourfile.ext"); //reading
File
、StreamWriter
和 StreamReader
类。