2 回答

TA貢獻1842條經驗 獲得超21個贊
你這樣做的方式是最好的方式,因為
您不想一次將整個文件讀入 RAM
您的線路處理獨立于以前的線路
抱歉,從硬盤讀取內容很慢。
改進可能來自其他來源:
將您的文件存儲在更快的設備(SSD?)
獲得更多 RAM 以將文件讀入內存以至少加快處理速度

TA貢獻1829條經驗 獲得超7個贊
首先,您需要讀取整個文件還是僅讀取文件的一部分。
如果您只需要讀取文件的部分
const int chunkSize = 1024; // read the file by chunks of 1KB
using (var file = File.OpenRead("yourfile"))
{
int bytesRead;
var buffer = new byte[chunkSize];
while ((bytesRead = file.Read(buffer, 0 /* start offset */, buffer.Length)) > 0)
{
// TODO: Process bytesRead number of bytes from the buffer
// not the entire buffer as the size of the buffer is 1KB
// whereas the actual number of bytes that are read are
// stored in the bytesRead integer.
}
}
如果需要將整個文件加載到內存中。
重復使用此方法而不是直接加載到內存中,因為您可以控制正在執行的操作,并且可以隨時停止該過程。
或者您可以使用https://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.aspx?f=255&MSPPError=-2147217396MemoryMappedFile
內存映射文件將提供從內存訪問的程序視圖,但它只會第一次從磁盤加載。
long offset = 0x10000000; // 256 megabytes
long length = 0x20000000; // 512 megabytes
// Create the memory-mapped file.
using (var mmf = MemoryMappedFile.CreateFromFile(@"c:\ExtremelyLargeImage.data", FileMode.Open,"ImgA"))
{
// Create a random access view, from the 256th megabyte (the offset)
// to the 768th megabyte (the offset plus length).
using (var accessor = mmf.CreateViewAccessor(offset, length))
{
//Your process
}
}
- 2 回答
- 0 關注
- 221 瀏覽
添加回答
舉報