c#读取超大文本文件-速度快

c#读取超大文本文件-速度快

   private string ReadTxtFile(string fileName)
        {
 
            string txt = "";
            // var fileDir = this.txtFileFolder.Text.Trim();
            var fileDir = fileName;
 
            byte[] allBytes = null;
 
            byte[] buffer = new byte[1024];//一个1K的缓冲字节容器
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Restart();
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(fileDir, FileMode.Open, FileAccess.Read))
                {
                    int positon = 0;
                    while ((positon = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, positon);
 
                    }
 
                    allBytes = ms.ToArray();
                }
 
            }
            stopwatch.Stop();
            // MessageBox.Show($"StreamReader StreamWriter 程序运行花费的时间:{(double)stopwatch.ElapsedMilliseconds / 1000:0.000} secs");
 
            if (null != allBytes)
            {
                //尝试将字节转成字符串
                txt = System.Text.Encoding.UTF8.GetString(allBytes);
                // this.richTextBox_Result.Text = txt;
 
            }
            string[] txtToArray = txt.Split('\r');
            //  ReadData_List.Add(txtToArray);
            return txt;
 
        }

 

posted @ 2022-01-12 11:38  txwtech  阅读(1601)  评论(1编辑  收藏  举报