我想使用.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.