小编spr*_*hun的帖子

如何在 C# 中使用 FILE_FLAG_NO_BUFFERING 调用 win32 CreateFile api 禁用磁盘缓存

大家,我每秒有很多文件写入磁盘,我想禁用磁盘缓存以提高性能,我谷歌搜索找到解决方案:win32 CreateFile method with FILE_FLAG_NO_BUFFERING 和 How toempty /flush Windows READ disk cache in C#?

我写了一些代码来测试是否可以工作:

const int FILE_FLAG_NO_BUFFERING = unchecked((int)0x20000000);

[DllImport("KERNEL32", SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
static extern SafeFileHandle CreateFile(
      String fileName,
      int desiredAccess,
      System.IO.FileShare shareMode,
      IntPtr              securityAttrs,
      System.IO.FileMode  creationDisposition,
      int                 flagsAndAttributes,
      IntPtr              templateFile);

static void Main(string[] args)
{
    var handler = CreateFile(@"d:\temp.bin", (int)FileAccess.Write, FileShare.None,IntPtr.Zero, FileMode.Create, FILE_FLAG_NO_BUFFERING, IntPtr.Zero);
    var stream = new FileStream(handler, FileAccess.Write, BlockSize);//BlockSize=4096
    byte[] array = Encoding.UTF8.GetBytes("hello,world");
    stream.Write(array, 0, array.Length);
    stream.Close();
} …
Run Code Online (Sandbox Code Playgroud)

c# pinvoke filestream createfile

2
推荐指数
1
解决办法
3936
查看次数

标签 统计

c# ×1

createfile ×1

filestream ×1

pinvoke ×1