华为手机_text是什么文件_C# 读写txt文件方法

本文详细介绍了使用C#进行文件操作的方法,包括利用File类和Stream类进行文本文件的读写操作。通过实例展示了如何创建文件、写入内容、读取文件等基本功能,并提供了错误处理技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加引用:

using System.IO;

1.File类写入文本文件:

private void btnTextWrite_Click(objectsender, EventArgs e)

{//文件路径

string filePath = @"E:\123\456.txt";//检测文件夹是否存在,不存在则创建

NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly));//定义编码方式,text1.Text为文本框控件中的内容

byte[] mybyte =Encoding.UTF8.GetBytes(text1.Text);string mystr1 =Encoding.UTF8.GetString(mybyte);//写入文件//File.WriteAllBytes(filePath,mybyte);//写入新文件//File.WriteAllText(filePath, mystr1);//写入新文件

File.AppendAllText(filePath, mystr1);//添加至文件

}

2.File类读取文本文件:

private void btnTexRead_Click(objectsender, EventArgs e)

{//文件路径

string filePath = @"E:\123\456.txt";try{if(File.Exists(filePath))

{

text1.Text=File.ReadAllText(filePath);byte[] mybyte =Encoding.UTF8.GetBytes(text1.Text);

text1.Text=Encoding.UTF8.GetString(mybyte);

}else{

MessageBox.Show("文件不存在");

}

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

3.StreamWrite类写入文本文件:

private void btnTextWrite_Click(objectsender, EventArgs e)

{//文件路径

string filePath = @"E:\123\456.txt";try{//检测文件夹是否存在,不存在则创建

string mystr1 =NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly));using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))

{byte[] mybyte =Encoding.UTF8.GetBytes(text1.Text);

text1.Text=Encoding.UTF8.GetString(mybyte);

sw.Write(text1.Text);

}

}catch{

}

}

4.StreamReader类读取文本文档:

private void btnTexRead_Click(objectsender, EventArgs e)

{//文件路径

string filePath = @"E:\123\456.txt";try{if(File.Exists(filePath))

{using (StreamReader sr = newStreamReader(filePath, Encoding.UTF8))

{

text1.Text=sr.ReadToEnd();byte[] mybyte =Encoding.UTF8.GetBytes(text1.Text);

text1.Text=Encoding.UTF8.GetString(mybyte);

}

}else{

MessageBox.Show("文件不存在");

}

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

----------------------------------------------------------------------------------------------

遇到的常见错误:

1.ERROR: “System.Web.Mvc.Controller.File(string, string, string)”是一个“方法”,这在给定的上下文中无效

解决方法:Controller.File方法和System.IO.File类名称冲突的问题,只要完整输入明确类名就可解决。

例如:File.ReadAllText();  改为  System.IO.File.ReadAllText();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值