C# 文件读取怎么屏蔽硬盘缓存?

问题遇到的现象和发生背景

我要做个硬盘读写测试工具。用的FileStream。

遇到的现象和发生背景,请写出第一个错误信息

下面是我用FileStream对文件的读写方法,方法没有问题,都正常的

用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
public void io(string path, string path2)
        {

            DateTime time1 = DateTime.Now;
            //写入
            FileStream writefs = new FileStream(path, FileMode.Create, FileAccess.Write);//写入
            byte[] buffer2 = new byte[1073741824];//1G缓存
            writefs.Write(buffer2, 0, Convert.ToInt32(1073741824));
            writefs.Close(); 
            DateTime time2 = DateTime.Now;
            // 读取
            FileStream readfs = new FileStream(path2, FileMode.Open, FileAccess.Read);
            readfs.Read(buffer2, 0, Convert.ToInt32(1073741824));
            readfs.Close();
            DateTime time3 = DateTime.Now;

            //写入时间
            TimeSpan ts1 = time2.Subtract(time1);
            //读取时间
            TimeSpan ts2 = time3.Subtract(time2);
            MessageBox.Show("写入时间:" + ts1.Seconds.ToString()+ " 读取时间:" + ts2.Seconds.ToString());
        }

运行结果及详细报错内容

读文件的时候只有第一次是直接从硬盘读取。之后好像就是从硬盘缓存读取了,因为读取用的时间都是0。程序重开也一样。

我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%

如何才能绕开这个硬盘缓存,或者每次运行清除缓存/

我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”

On Windows you can disable buffering by passing FILE_FLAG_NO_BUFFERING flag in FileOptions options parameter of stream constructor. There's no such value in FileOptions enum and you have to pass it's numerical value (0x2000000 - this value is found in FileStream source codes and is treated as valid).

readStream = new FileStream(
      path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, buffer, (FileOptions)0x20000000);

可以尝试在读文件之前,使用 FlushFileBuffers 函数清除文件的系统缓存:

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FlushFileBuffers(SafeFileHandle hFile);

// 在读文件之前调用
FlushFileBuffers(readfs.SafeFileHandle);

FlushFileBuffers 函数仅能清除文件的系统缓存,不能清除硬盘高速缓存。如果想要清除硬盘高速缓存,可以尝试使用软件工具来完成。

还可以使用带有 FILE_FLAG_NO_BUFFERING 参数的 CreateFile 函数来创建文件,这样就可以绕开系统的缓存机制。但是这会对性能产生负面影响,因此不推荐使用。

你可以使用 .NET Framework 中的 Flush 方法来清除硬盘缓存,这样就可以保证每次读取文件时都是直接从硬盘读取。

你可以将下面的代码插入到你的代码中,在写入文件之后使用 Flush 方法清除硬盘缓存:

writefs.Flush(true);


这样你就可以在每次读取文件时都能直接从硬盘读取,而不是从硬盘缓存中读取。

另外,你也可以使用 FileOptions.NoBuffering 选项来禁用硬盘缓存,这样你就可以直接从硬盘读取文件,而不会被硬盘缓存影响。你可以在创建 FileStream 对象时使用这个选项,例如:

FileStream readfs = new FileStream(path2, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.None);