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

前端之家收集整理的这篇文章主要介绍了c# – 使用.NET中的NTFS压缩压缩文件夹前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用.NET中的NTFS压缩压缩文件夹.我发现 this post,但它不工作.它引发异常(“无效参数”).
  1. DirectoryInfo directoryInfo = new DirectoryInfo( destinationDir );
  2. if( ( directoryInfo.Attributes & FileAttributes.Compressed ) != FileAttributes.Compressed )
  3. {
  4. string objPath = "Win32_Directory.Name=" + "\"" + destinationDir + "\"";
  5. using( ManagementObject dir = new ManagementObject( objPath ) )
  6. {
  7. ManagementBaSEObject outParams = dir.InvokeMethod( "Compress",null,null );
  8. uint ret = (uint)( outParams.Properties["ReturnValue"].Value );
  9. }
  10. }

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

解决方法

根据我的经验,使用P / Invoke通常比WMI更容易.我相信以下内容应该有效:
  1. private const int FSCTL_SET_COMPRESSION = 0x9C040;
  2. private const short COMPRESSION_FORMAT_DEFAULT = 1;
  3.  
  4. [DllImport("kernel32.dll",SetLastError = true)]
  5. private static extern int DeviceIoControl(
  6. SafeFileHandle hDevice,int dwIoControlCode,ref short lpInBuffer,int nInBufferSize,IntPtr lpOutBuffer,int nOutBufferSize,ref int lpBytesReturned,IntPtr lpOverlapped);
  7.  
  8. public static bool EnableCompression(SafeFileHandle handle)
  9. {
  10. int lpBytesReturned = 0;
  11. short lpInBuffer = COMPRESSION_FORMAT_DEFAULT;
  12.  
  13. return DeviceIoControl(handle,FSCTL_SET_COMPRESSION,ref lpInBuffer,sizeof(short),IntPtr.Zero,ref lpBytesReturned,IntPtr.Zero) != 0;
  14. }

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

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

猜你在找的C#相关文章