I am making a program and I have absolutely no clue how to read and write a text file. I would like it so that I only need one text file that has all kinds of data, so I need to be able to read specific lines of the file.
问问题
68 次
3 回答
1
You can use StreamReader
and StreamWriter
classes:
StreamReader sr = new StreamReader("C:\\Sample.txt");
var data = sr.ReadLine();
StreamWriter sw = new StreamWriter("C:\\Test.txt");
sw.WriteLine("Hello World!!");
Taken from: http://support.microsoft.com/kb/816149.
EDIT: To clarify, always close the streams. sr.Close()
sw.Close()
. Or wrap them within a using
statement just as James did on his answer.
于 2013-10-19T17:56:22.303 回答
0
using (System.IO.StreamReader sr = new System.IO.StreamReader("YourFile.txt"))
{
String line = sr.ReadLine();
Console.WriteLine(line);
}
于 2013-10-19T17:59:30.803 回答
0
you can also use the File class.
string h1 = File.ReadAllText("D:\\TempFiles\\h1.txt");
string h1 = File.WriteAllText("D:\\TempFiles\\h1.txt");
于 2013-10-19T20:26:53.367 回答