C#读取文件高效方法实现
C# Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
private void button1_Click(object sender, EventArgs e)
{ var fileDir = this.txtFileFolder.Text.Trim(); byte[] allBytes = null; byte[] buffer = new byte[1024];//一个1K的缓冲字节容器 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(); } } if (null!=allBytes) { //尝试将字节转成字符串 var txt = System.Text.Encoding.UTF8.GetString(allBytes); this.richTextBox_Result.Text = txt; } } |