有人知道将文件从路径A复制到路径B并抑制Windows文件系统缓存的方法吗?
典型用途是将大型文件从USB驱动器或服务器复制到本地计算机.如果文件非常大,Windows似乎会将所有内容都换掉,例如2GiB.首选C#中的示例,但我猜这将是某种Win32调用,如果可能的话.
在C#中,我发现这样的东西可以工作,可以将其更改为直接复制到目标文件:
public static byte[] ReadAllBytesUnbuffered(string filePath) { const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000; var fileInfo = new FileInfo(filePath); long fileLength = fileInfo.Length; int bufferSize = (int)Math.Min(fileLength, int.MaxValue / 2); bufferSize += ((bufferSize + 1023) & ~1023) - bufferSize; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, bufferSize, FileFlagNoBuffering | FileOptions.SequentialScan)) { long length = stream.Length; if (length > 0x7fffffffL) { throw new IOException("File too long over 2GB"); } int offset = 0; int count = (int)length; var buffer = new byte[count]; while (count > 0) { int bytesRead = stream.Read(buffer, offset, count); if (bytesRead == 0) { throw new EndOfStreamException("Read beyond end of file EOF"); } offset += bytesRead; count -= bytesRead; } return buffer; } }
更重要的是,有FILE_FLAG_WRITE_THROUGH和FILE_FLAG_NO_BUFFERING.
MSDN上有一篇很好的文章:http://support.microsoft.com/kb/99794