-
C#教程之C#教程之C#读写文本文件的方法
本站最新发布 C#从入门到精通
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
本文实例讲述了C#读写文本文件的方法。分享给大家供大家参考。具体分析如下:
System.IO命名空间中的类为托管应用程序提供文件以及其他形式的输入输出。托管i/o的基本构件是流,而流是字节导向的数据的抽象表示。流通过System.IO.Stream类表示.
System.IO.FileStream允许将文件作为流访问;
System.IO.MemoryStream允许将内存块作为流进行访问
以下为读写文件的示例
先引用命名空间
using System.IO;
以下是源代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
namespace 文本文件打开测试 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_Read_Click( object sender, EventArgs e) { //异常检测开始 try { FileStream fs = new FileStream(@tB_PachFileName.Text , FileMode.Open, FileAccess.Read); //读取文件设定 StreamReader m_streamReader = new StreamReader(fs, System.Text.Encoding.GetEncoding( "GB2312" )); //设定读写的编码 //使用StreamReader类来读取文件 m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin); // 从数据流中读取每一行,直到文件的最后一行,并在rTB_Display.Text中显示出内容 this .rTB_Display.Text = "" ; string strLine = m_streamReader.ReadLine(); while (strLine != null ) { this .rTB_Display.Text += strLine + "\n" ; strLine = m_streamReader.ReadLine(); } //关闭此StreamReader对象 m_streamReader.Close(); } catch { //抛出异常 MessageBox.Show( "指定文件不存在" ); return ; } //异常检测结束 } private void btn_Replace_Click( object sender, EventArgs e) { //判断替换开始 if (tB_Replace.Text == "" &&tB_Replace_2.Text== "" ) { MessageBox.Show( "想替换的字符都没有就换啊,你太有才了" ); } else { if (rTB_Display.Text == "" ) { MessageBox.Show( "文件内容为空无法进行替换,请检查文件" ); } else { string str = rTB_Display.Text.ToString(); rTB_Display.Text = str.Replace(@tB_Replace.Text ,@tB_Replace_2.Text); //替换 } } //结束 } private void btn_Save_Click( object sender, EventArgs e) { //异常检测开始 try { //创建一个文件流,用以写入或者创建一个StreamWriter FileStream fs = new FileStream(@tB_Save.Text, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.Flush(); // 使用StreamWriter来往文件中写入内容 m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin); // 把richTextBox1中的内容写入文件 m_streamWriter.Write(rTB_Display.Text); //关闭此文件 m_streamWriter.Flush(); m_streamWriter.Close(); } catch { //抛出异常 MessageBox.Show( "写入文件失败,请检查路径 文件名与权限是否符合" ); } //异常检测结束 } } } |
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能