如何读取和写入到文本文件中,通过使用 Visual C#

读取文本文件
若要打开、 读取,和来关闭文本文件,下面的代码使用 StreamReader 类。您可以将文本文件的路径传递给 StreamReader 构造函数自动打开该文件。ReadLine 方法读取的每一行文本,并读取递增到下一行将文件指针。当 ReadLine 方法到达文件结尾时, 它将返回空引用。
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");

//Read the first line of text
line = sr.ReadLine();

//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}

//close the file
sr.Close();
Console.ReadLine();
写文本文件 (示例 1)
下面的代码使用 StreamWriter 类打开、 写入,和以关闭该文本文件。StreamReader 类以类似方式您可以将文本文件的路径传递给该 StreamWriter 构造函数,以自动打开该文件。WriteLine 方法写入文本文件的完整文本行。
try
{

//Pass the filepath and filename to the StreamWriter Constructor
StreamWriter sw = new StreamWriter("C:\\Test.txt");

//Write a line of text
sw.WriteLine("Hello World!!");

//Write a second line of text
sw.WriteLine("From the StreamWriter class");

//Close the file
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
写文本文件 (示例 2)
下面的代码使用 StreamWriter 类打开、 写入,和以关闭该文本文件。与前面的示例不同此代码将两个附加参数传递给构造函数。第一个参数是该文件的路径和文件的文件名。第二个参数 为 True,指定打开该文件中追加模式。如果您在第二个参数指定 False,该文件的内容将覆盖每次运行该代码。第三个参数指定 Unicode,以便 StreamWriter 对该文件以 Unicode 格式进行编码。 您还可以指定下列编码方法的第三个参数:

* ASC11
* Unicode
* UTF7
* UTF8

Write 方法是与 WriteLine 方法类似,不同之处在于 Write 方法不会自动嵌入回车或换行 (CR/LF) 字符组合。当您想要一次写入一个字符时,这是很有用。
Int64 x;

try
{
//Open the File
StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);

//Writeout the numbers 1 to 10 on the same line.
for(x=0; x < 10; x++)
{
sw.Write(x);
}

//close the file
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值