日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C#读写文本文件

發布時間:2023/12/10 C# 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#读写文本文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

C#中讀寫文本文件.txt文件既可以用File類也可用StreamReader、StreamWrite類。這兩種方法都需要引用using System.IO命名空間。

下面分別給出例子:

1.File類寫入文本文件:

1 private void btnTextWrite_Click(object sender, EventArgs e) 2 { 3 //文件路徑 4 string filePath = @"E:\123\456.txt"; 5 6 //檢測文件夾是否存在,不存在則創建 7 NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly)); 8 9 //定義編碼方式,text1.Text為文本框控件中的內容 10 byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text); 11 string mystr1 = Encoding.UTF8.GetString(mybyte); 12 13 //寫入文件 14 //File.WriteAllBytes(filePath,mybyte);//寫入新文件 15 //File.WriteAllText(filePath, mystr1);//寫入新文件 16 File.AppendAllText(filePath, mystr1);//添加至文件 17 18 }

?

2.File類讀取文本文件:

1 private void btnTexRead_Click(object sender, EventArgs e) 2 { 3 //文件路徑 4 string filePath = @"E:\123\456.txt"; 5 try 6 { 7 if (File.Exists(filePath)) 8 { 9 text1.Text = File.ReadAllText(filePath); 10 byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text); 11 text1.Text = Encoding.UTF8.GetString(mybyte); 12 } 13 else 14 { 15 MessageBox.Show("文件不存在"); 16 } 17 } 18 catch (Exception ex) 19 { 20 MessageBox.Show(ex.Message); 21 } 22 }

?

3.StreamWrite類寫入文本文件:

1 private void btnTextWrite_Click(object sender, EventArgs e) 2 { 3 //文件路徑 4 string filePath = @"E:\123\456.txt"; 5 6 try 7 { 8 //檢測文件夾是否存在,不存在則創建 9 string mystr1 = NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly)); 10 11 using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8)) 12 { 13 byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text); 14 text1.Text = Encoding.UTF8.GetString(mybyte); 15 sw.Write(text1.Text); 16 } 17 18 } 19 catch 20 { 21 22 } 23 }

?

4.StreamReader類讀取文本文檔:

1 private void btnTexRead_Click(object sender, EventArgs e) 2 { 3 //文件路徑 4 string filePath = @"E:\123\456.txt"; 5 try 6 { 7 if (File.Exists(filePath)) 8 { 9 using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8)) 10 { 11 text1.Text = sr.ReadToEnd(); 12 byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text); 13 text1.Text = Encoding.UTF8.GetString(mybyte); 14 } 15 } 16 else 17 { 18 MessageBox.Show("文件不存在"); 19 } 20 } 21 catch (Exception ex) 22 { 23 MessageBox.Show(ex.Message); 24 } 25 }

?

轉載于:https://www.cnblogs.com/nicewe/p/8616261.html

總結

以上是生活随笔為你收集整理的C#读写文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。