c# - 设置文件压缩属性

标签 c# compression ntfs file-attributes

我期望这段代码:

if (!File.Exists(fullFileName))
{
    File.Create(fullFileName);
}

File.SetAttributes(fullFileName, FileAttributes.Compressed);

要设置这个标志:

enter image description here

但它没有...我做错了什么?如何在文件上设置该标志?


更新:它说 in the documentation

"It is not possible to change the compression status of a File object using the SetAttributes method."

而且显然它在使用静态 File.SetAttributes 时也不起作用。

鉴于此,如何实现这一点?

最佳答案

您可以使用 p/invoke 来压缩文件。

我给自己做了一个静态辅助函数:

public static class FileTools
{
  private const int FSCTL_SET_COMPRESSION = 0x9C040;
  private const short COMPRESSION_FORMAT_DEFAULT = 1;

  [DllImport("kernel32.dll", SetLastError = true)]
  private static extern int DeviceIoControl(
      IntPtr hDevice,
      int dwIoControlCode,
      ref short lpInBuffer,
      int nInBufferSize,
      IntPtr lpOutBuffer,
      int nOutBufferSize,
      ref int lpBytesReturned,
      IntPtr lpOverlapped);

  public static bool EnableCompression(IntPtr handle)
  {
    int lpBytesReturned = 0;
    short lpInBuffer = COMPRESSION_FORMAT_DEFAULT;

    return DeviceIoControl(handle, FSCTL_SET_COMPRESSION,
        ref lpInBuffer, sizeof(short), IntPtr.Zero, 0,
        ref lpBytesReturned, IntPtr.Zero) != 0;
  }
}

例如,我在代码中使用文件名:

using (var fileToCompress = File.Open(fileNameToCompress, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
  FileTools.EnableCompression(fileToCompress.Handle);

关于c# - 设置文件压缩属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31032834/

相关文章:

c# - ASP.NET 从内容页面更改 facebook og 属性

c# - 嵌套接口(interface)和抽象实现类

compression - zlib、gzip 和 zip 有什么关系?它们有什么共同点,又有什么不同?

compression - Apache Spark 中的 Zip 支持

mysql - 在开发机器上移动 MySQL datadir

c# - WebBrowser 控件禁用鼠标点击

c# - 从包含变量的C#执行多个Powershell命令

azure - 如何使用 Bicep 激活 Azure Front Door 路线的压缩?

windows - 修改NTFS主文件表(MFT)中的文件记录失败

node.js - Nodejs + npm,在 ntfs 分区上安装模块