建设厅的工程造价网站,东莞网站优化方式,怎样在外贸网站上做土特产,wordpress 整站加密C#中读写文本文件.txt文件既可以用File类也可用StreamReader、StreamWrite类。这两种方法都需要引用using System.IO命名空间。 下面分别给出例子#xff1a; 1.File类写入文本文件#xff1a; 1 private void btnTextWrite_Click(object sender, EventArgs e)2 …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 try6 {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 try7 {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 try6 {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