C#文本文件操作

如何向现有文件中添加文本
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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值