如何向现有文件中添加文本
usingSystem;
usingSystem.IO;
classTest
{
publicstaticvoidMain()
{
//CreateaninstanceofStreamWritertowritetexttoafile.
//TheusingstatementalsoclosestheStreamWriter.
using(StreamWritersw=newStreamWriter("TestFile.txt"))
{
//Addsometexttothefile.
sw.Write("Thisisthe");
sw.WriteLine("headerforthefile.");
sw.WriteLine("-------------------");
//Arbitraryobjectscanalsobewrittentothefile.
sw.Write("Thedateis:");
sw.WriteLine(DateTime.Now);
}
}
}
如何创建一个新文本文件并向其中写入一个字符串。<link keywords="Overload:System.IO.FileSystem.WriteAllText">方法可提供类似的功能。
usingSystem;
usingSystem.IO;
publicclassTextToFile
{
privateconststringFILE_NAME="MyFile.txt";
publicstaticvoidMain(String[]args)
{
if(File.Exists(FILE_NAME))
{
Console.WriteLine("{0}alreadyexists.",FILE_NAME);
return;
}
using(StreamWritersw=File.CreateText(FILE_NAME))
{
sw.WriteLine("Thisismyfile.");
sw.WriteLine("Icanwriteints{0}orfloats{1},andsoon.",
1,4.2);
sw.Close();
}
}
}
如何从文本文件中读取文本
usingSystem;
usingSystem.IO;
classTest
{
publicstaticvoidMain()
{
try
{
//CreateaninstanceofStreamReadertoreadfromafile.
//TheusingstatementalsoclosestheStreamReader.
using(StreamReadersr=newStreamReader("TestFile.txt"))
{
Stringline;
//Readanddisplaylinesfromthefileuntiltheendof
//thefileisreached.
while((line=sr.ReadLine())!=null)
{
Console.WriteLine(line);
}
}
}
catch(Exceptione)
{
//Lettheuserknowwhatwentwrong.
Console.WriteLine("Thefilecouldnotberead:");
Console.WriteLine(e.Message);
}
}
}
在检测到文件结尾时向您发出通知。通过使用<link keywords="Overload:System.IO.File.ReadAll">或<link keywords="Overload:System.IO.File.ReadAllText">方法也可以实现此功能。
usingSystem;
usingSystem.IO;
publicclassTextFromFile
{
privateconststringFILE_NAME="MyFile.txt";
publicstaticvoidMain(String[]args)
{
if(!File.Exists(FILE_NAME))
{
Console.WriteLine("{0}doesnotexist.",FILE_NAME);
return;
}
using(StreamReadersr=File.OpenText(FILE_NAME))
{
Stringinput;
while((input=sr.ReadLine())!=null)
{
Console.WriteLine(input);
}
Console.WriteLine("Theendofthestreamhasbeenreached.");
sr.Close();
}
}