原文: C# 讀取大檔案 (可以讀取3GB大小的txt檔案)
在處理大資料時,有可能 會碰到 超過3GB大小的檔案,如果通過 記事本 或 NotePad++去打開它,會報錯,讀不到任何檔案。
如果你隻是希望讀取這檔案中的前幾行,怎麼辦,下面的工具會幫您解決這個問題. 而且讀取時間很快。
截圖:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZlBnauQ2Y1MTO3EjMwUGN4QGNiRDZyUDNwMjYhVjNzE2YkZWMfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.jpeg)
工具下載下傳位址: http://pan.baidu.com/s/1y34wt (15KB左右, 備注:要運作這個工具,需要您的機器已裝過 .netFramework4.0 )
源代碼下載下傳位址:http://pan.baidu.com/s/1jAyjl (70KB左右)
源代碼樣例:
1,讀取一般檔案的代碼
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的文本檔案)
private bool ReadBigFile()
{
string sTmpFile=@"c:\tmpTest.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);
}
}