C#——读文件方法(Filestream、File、StreamReader)

方法一:使用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);
                textBox.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();
                }
                textBox.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();
 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值