在c#中有很多不同的方法来读写文件(文本文件,而不是二进制文件)。
我只需要一些简单的东西,使用最少的代码,因为我将在我的项目中大量使用文件。我只需要一些字符串,因为我所需要的是读写字符串。
在c#中有很多不同的方法来读写文件(文本文件,而不是二进制文件)。
我只需要一些简单的东西,使用最少的代码,因为我将在我的项目中大量使用文件。我只需要一些字符串,因为我所需要的是读写字符串。
当前回答
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
}
其他回答
除了文件。ReadAllText,文件。ReadAllLines和File。WriteAllText(和类似的帮助从文件类)显示在另一个答案,你可以使用StreamWriter/StreamReader类。
写入文本文件:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
读取文本文件:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
注:
您可以使用readtext.Dispose()而不是using,但它不会在异常情况下关闭文件/读取器/写入器 请注意,相对路径是相对于当前工作目录。您可能希望使用/构造绝对路径。 缺少使用/Close是“为什么数据不写入文件”的常见原因。
简单:
String inputText = "Hello World!";
File.WriteAllText("yourfile.ext",inputText); //writing
var outputText = File.ReadAllText("yourfile.ext"); //reading
或者,如果你真的很注重线条:
System.IO.File也包含一个静态方法WriteAllLines,所以你可以这样做:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);
使用文件。ReadAllText和File.WriteAllText。
MSDN示例节选:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);
在读取时使用OpenFileDialog控件浏览到您想要读取的任何文件是很好的。找到下面的代码:
不要忘记添加以下using语句来读取文件:using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
要写入文件,可以使用File.WriteAllText方法。