写入/读取文本文件-C#

你好:

在本文中:您将学习写入或读取文本文件。

让我们开始:

首先创建一个新项目(ConsoleApp或WinApp)。

并且确保您的程序使用以下名称空间:


using System;
using System.IO;
using System.Diagnostics; 
现在,我们将开始将文本写入文件:

1)-创建一个新的流编写器并打开文件:


TextWriter tw = new StreamWriter(@"C:\Hello.txt"); 
2)-将文字写入档案:

tw.WriteLine("Hello"); 
3)-关闭文件。

tw.Close(); 
4)-启动文件:

Process.Start(@"C:\Hello.txt"); 
这是所有代码:

//Creating a new stream-writer and opening the file.
TextWriter tsw = new StreamWriter(@"C:\Hello.txt"); 
//Writing text to the file.
tsw.WriteLine("Hello"); 
//Close the file.
tsw.Close(); 
//Launch the file.
Process.Start(@"C:\Hello.txt"); 
Console.WriteLine("You're done, press any key to exit...");
Console.ReadKey(); 
现在,我们将开始从文件读取文本:

1)-创建一个新的流读取器并打开文件:


TextReader trs = new StreamReader(@"C:\Hello.txt"); 
2)-读取文件的文本:

//Reading all the text of the file.
Console.WriteLine(trs.ReadToEnd()); 
//Or Can Reading a line of the text file.
//Console.WriteLine(trs.ReadLine()); 
3)-关闭文件:

trs.Close(); 
这是所有代码:

//Creating a new stream-reader and opening the file.
TextReader trs = new StreamReader(@"C:\Hello.txt"); 
//Reading all the text of the file.
Console.WriteLine(trs.ReadToEnd()); 
//Or Can Reading a line of the text file.
//Console.WriteLine(trs.ReadLine()); 
//Close the file.
trs.Close(); 
Console.WriteLine("Press any key to exit...");
Console.ReadKey(); 
希望这对您有所帮助。

From: https://bytes.com/topic/net/insights/673819-write-read-text-file-c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值