微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 使用.NET中的NTFS压缩压缩文件夹

我想使用.NET中的NTFS压缩压缩文件夹.我发现 this post,但它不工作.它引发异常(“无效参数”).
DirectoryInfo directoryInfo = new DirectoryInfo( destinationDir );
if( ( directoryInfo.Attributes & FileAttributes.Compressed ) != FileAttributes.Compressed )
{
   string objPath = "Win32_Directory.Name=" + "\"" + destinationDir + "\"";
   using( ManagementObject dir = new ManagementObject( objPath ) )
   {
      ManagementBaSEObject outParams = dir.InvokeMethod( "Compress",null,null );
      uint ret = (uint)( outParams.Properties["ReturnValue"].Value );
   }
}

有人知道如何在文件夹上启用NTFS压缩?

解决方法

根据我的经验,使用P / Invoke通常比WMI更容易.我相信以下内容应该有效:
private const int FSCTL_SET_COMPRESSION = 0x9C040;
private const short COMPRESSION_FORMAT_DEFAULT = 1;

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

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

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

由于您尝试将其设置在目录中,您可能需要使用P / Invoke才能使用FILE_FLAG_BACKUP_SEMANTICS调用CreateFile获取目录中的SafeFileHandle.

另外请注意,在NTFS目录中设置压缩不会压缩所有内容,它只会使新文件显示为压缩(加密也是如此).如果要压缩整个目录,则需要遍历整个目录,并在每个文件/文件夹中调用DeviceIoControl.

原文地址:https://www.jb51.cc/csharp/95075.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐