加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:39:16 所属栏目:百科 来源:网络整理
导读:我想使用.NET中的NTFS压缩压缩文件夹.我发现 this post,但它不工作.它引发异常(“无效参数”). DirectoryInfo directoryInfo = new DirectoryInfo( destinationDir );if( ( directoryInfo.Attributes FileAttributes.Compressed ) != FileAttributes.Compres
我想使用.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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读