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);
                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”

猜你喜欢

转载自www.cnblogs.com/icaowu/p/12059151.html
今日推荐