C#读操作(字节/字符)Filestream、File、StreamReader

写文件官方demo

https://docs.microsoft.com/zh-cn/dotnet/api/system.io.streamreader.readline?redirectedfrom=MSDN&view=netframework-4.8

 

 

方法一:使用Filestream,将文本一次性全部转换为字节,之后转换为string显示在text中

复制代码
OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "文本文件|*.txt";       //打开文件的类型
            if (fd.ShowDialog() == DialogResult.OK)
            {
                fn = fd.FileName;
                FileStream fs = new FileStream(fn, FileMode.Open, FileAccess.Read);
                int n = (int)fs.Length;
                byte[] b = new byte[n];
                int r = fs.Read(b, 0, n);
                textBox3.Text = Encoding.Default.GetString(b, 0, n);
复制代码

方法二:使用Filestream,逐字节读取文本,后将字节转换为string显示在text中

复制代码
FileStream fs = new FileStream(fn, FileMode.Open, FileAccess.Read);
                long n = fs.Length;
                byte[] b = new byte[n];
                int cnt, m;
                m = 0;
                cnt = fs.ReadByte();
                while (cnt != -1)
                {
                    b[m++] = Convert.ToByte(cnt);
                    cnt = fs.ReadByte();
                }
textBox3.Text = Encoding.Default.GetString(b)
复制代码

方法三:直接使用File的Read All Text 函数将文本文件内容全部读入text

textBox.Text = File.ReadAllText(fn, Encoding.Default);

方法四:使用StreamReader,将文本中的的内容逐行读入text

StreamReader sr = new StreamReader(fn, Encoding.Default);
                string line = sr.ReadLine();
                while (line != null)
                {
                    textBox.Text = textBox.Text + line + "\r\n";
                    line = sr.ReadLine();
                }

方法五:使用StreamReader中的ReadToEnd()函数,将文本中的内容全部读入text

StreamReader sr = new StreamReader(fn, Encoding.Default);
                textBox.Text = sr.ReadToEnd();

 

来源“https://blog.csdn.net/swin16/article/details/80256123”

 

注解

TextReader 类是抽象类。 因此,不要在代码中对其进行实例化。 StreamReader 类派生自 TextReader,并提供成员的实现以从流中读取。 下面的示例演示如何使用 StreamReader.ReadAsync(Char[], Int32, Int32) 方法读取文件中的所有字符。 它在将字符添加到 StringBuilder 类的实例之前,检查每个字符是否为字母、数字或空格。

注解

TextReader 是 StreamReader 和 StringReader的抽象基类,分别从流和字符串读取字符。 使用这些派生类打开文本文件以读取指定范围内的字符,或创建基于现有流的读取器。

https://docs.microsoft.com/zh-cn/dotnet/api/system.io.textreader?redirectedfrom=MSDN&view=netframework-4.8

posted @   流水江湖  阅读(2654)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示