我想在.NET中使用NTFS压缩来压缩文件夹.我找到了这篇文章,但它不起作用.它抛出异常("无效参数").
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, 0, ref lpBytesReturned, IntPtr.Zero) != 0; }
既然你要设置此上的目录,你可能会需要使用P/Invoke来调用的CreateFile使用FILE_FLAG_BACKUP_SEMANTICS
,以获得SafeFileHandle上的目录.
另请注意,在NTFS中对目录设置压缩不会压缩所有内容,它只会使新文件显示为压缩(加密也是如此).如果要压缩整个目录,则需要遍历整个目录并在每个文件/文件夹上调用DeviceIoControl.
我已经测试了代码和它 !
确保它适用于gui.也许分配单元的大小对于压缩来说太大了.或者您没有足够的权限.
对于您的目标使用格式如下:"c:/ temp/testcomp"使用正斜杠.
完整代码:
using System.IO; using System.Management; class Program { static void Main(string[] args) { string destinationDir = "c:/temp/testcomp"; 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); } } } }