C#文件读取

找了几个方法

  Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();
            this.richTextBox1.Text = string.Empty;
            string line = string.Empty;
            StringBuilder sb = new StringBuilder();
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "txt文件|*.txt";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(dlg.FileName, Encoding.GetEncoding("GB2312"));
                int nchar;
                nchar = sr.Read();
                while (nchar != -1)
                {
                    sb.Append(Convert.ToChar(nchar).ToString());
                    nchar = sr.Read();

                }
                sr.Close();
                this.SetRichT(sb.ToString());
                sw.Stop();
                MessageBox.Show(sw.ElapsedMilliseconds.ToString());

            }

 测试文件174Mb

 耗时:

方法2

 Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();
            this.richTextBox1.Text = string.Empty;
            string line = string.Empty;
            StringBuilder sb = new StringBuilder();
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "txt文件|*.txt";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(dlg.FileName, Encoding.GetEncoding("GB2312"));
                while ((line = sr.ReadLine()) != null)
                {
                    sb.Append(line);

                }
                this.SetRichT(sb.ToString()); sw.Stop();
                MessageBox.Show(sw.ElapsedMilliseconds.ToString());
            }

耗时:

方法3

 Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();
            this.richTextBox1.Text = string.Empty;
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "txt文件|*.txt";
            string line = string.Empty;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(dlg.FileName, Encoding.GetEncoding("GB2312"));
                line = sr.ReadToEnd();
                this.SetRichT(line); sw.Stop();
                MessageBox.Show(sw.ElapsedMilliseconds.ToString());
            }
 
delegate void SetRitchText(object o);
        private void SetRichT(object o)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                this.richTextBox1.BeginInvoke(new SetRitchText(this.SetRichT), o);
            }
            else
            {

                this.richTextBox1.Text += o + "\r\n";
                this.textBox1.Text = o.ToString().Length.ToString();
            }
        }

 

posted @ 2013-07-04 22:33  永远的菜鸟@me  阅读(399)  评论(0编辑  收藏  举报