C# 读取大文件 (可以读取3GB大小的txt文件)
源代码样例:
1,读取一般文件的代码
[csharp] view plain copy

- public static string ReaderFile(string path)
- {
- string fileData = string.Empty;
- try
- { ///读取文件的内容
- StreamReader reader = new StreamReader(path, Encoding.Default);
- fileData = reader.ReadToEnd();
- reader.Close();
- }
- catch (Exception ex)
- {
- // throw new Exception(ex.Message,ex);
- } ///抛出异常
- return fileData;
- }
2, 读取 大文件(大到约4个GB的文本文件)
[csharp] view plain copy

- private bool ReadBigFile()
- {
- string sTmpFile=@"c: mpTest.txt";
- if (File.Exists(sTmpFile))
- {
- File.Delete(sTmpFile);
- }
- if (!System.IO.File.Exists(sTmpFile))
- {
- FileStream fs;
- fs = File.Create(sTmpFile);
- fs.Close();
- }
- if (!File.Exists(txtFileName.Text.Trim()))
- {
- lblResult.Text = "File not exist!";
- txtFileName.Focus();
- return false;
- }
- FileStream streamInput = System.IO.File.OpenRead(@txtFileName.Text.Trim());
- FileStream streamOutput = System.IO.File.OpenWrite(sTmpFile);
- int iRowCount = 10;
- int.TryParse(txtRowCount.Text.Trim(), out iRowCount);
- try
- {
- for (int i = 1; i <= iRowCount; )
- {
- int result = streamInput.ReadByte();
- if (result == 13)
- {
- i++;
- }
- if (result == -1)
- {
- break;
- }
- streamOutput.WriteByte((byte)result);
- }
- }
- finally
- {
- streamInput.Dispose();
- streamOutput.Dispose();
- }
- string sContent = ReaderFile(sTmpFile);
- CopyToClipboard(sContent);
- return true;
- }
- public static string ReaderFile(string path)
- {
- string fileData = string.Empty;
- try
- { ///读取文件的内容
- StreamReader reader = new StreamReader(path, Encoding.Default);
- fileData = reader.ReadToEnd();
- reader.Close();
- }
- catch (Exception ex)
- {
- // throw new Exception(ex.Message,ex);
- } ///抛出异常
- return fileData;
- }
- private void CopyToClipboard(string sSource)
- {
- Clipboard.Clear();
- if (!string.IsNullOrEmpty(sSource))
- {
- Clipboard.SetText(sSource);
- }
- }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 8. PHP接入微信的三种支付:APP支付、公众号支付、扫码支付
- 下一篇: 微信开发之扫码支付