我看到这个术语被频繁提及,但我不太明白如何在内存中打开文件。
我将文件写入临时位置的磁盘,但是当某个表单关闭时需要清理它,而在它打开时我无法这样做。这个文件夹必须被清空。我想知道如果我打开内存中的文件是否会有所不同?
MemoryStream inMemoryCopy = new MemoryStream();
using (FileStream fs = File.OpenRead(path))
{
fs.CopyTo(inMemoryCopy);
}
// Now you can delete the file at 'path' and still have an in memory copy
我认为您希望使用最近添加到.NET 4的内存映射文件进行工作。
FileStream
构造函数的DeleteOnClose
参数:FileStream fs = new FileStream("<Path Here>", FileMode.Create,
FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.DeleteOnClose);
并且当文件关闭时,该文件将被删除。
我认为这意味着将文件内容全部读入内存,然后关闭文件连接。假设这是一个不太大的文件,你可以直接将其读入byte[]中:
byte[] fileContent = File.ReadAllBytes(fileName);
string fileContent = File.ReadAllText(fileName);
完成上述步骤后,您可以使用StreamReader来读取它,就像在磁盘上读取文件一样。