调用API设置系统的压缩属性
最近应用到了这个:压缩属性, 可将文件或目录设置成压缩的以节省空间,使用C#的FileAttributes.Compressed无效
在网上找了些内容,最后的测试代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using Microsoft.Win32; 3 using System.IO; 4 using System.Runtime.InteropServices; 5 using Microsoft.Win32.SafeHandles; 6 7 namespace MuXueNtfsCompression 8 { 9 class Program 10 { 11 private const int FSCTL_SET_COMPRESSION = 0x9C040; 12 private const short COMPRESSION_FORMAT_DEFAULT = 1; 13 private const uint GENERIC_READ = 0x80000000; 14 private const uint GENERIC_WRITE = 0x40000000; 15 private const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; 16 17 [DllImport("kernel32.dll", SetLastError = true)] 18 private static extern int DeviceIoControl( 19 SafeFileHandle hDevice, 20 int dwIoControlCode, 21 ref short lpInBuffer, 22 int nInBufferSize, 23 IntPtr lpOutBuffer, 24 int nOutBufferSize, 25 ref int lpBytesReturned, 26 IntPtr lpOverlapped); 27 28 [DllImport("Kernel32.dll", EntryPoint = "CreateFile", SetLastError = true)] 29 private static extern SafeFileHandle CreateFile( 30 String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, 31 IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, 32 IntPtr hTemplateFile); 33 34 public static void EnableCompression(SafeFileHandle handle) 35 { 36 int lpBytesReturned = 0; 37 short lpInBuffer = COMPRESSION_FORMAT_DEFAULT; 38 39 int result = DeviceIoControl(handle, FSCTL_SET_COMPRESSION, 40 ref lpInBuffer, sizeof(short), IntPtr.Zero, 0, 41 ref lpBytesReturned, IntPtr.Zero); 42 43 if (result == 0) 44 { 45 Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); 46 } 47 48 handle.Close(); 49 } 50 51 static void Main(string[] args) 52 { 53 #region 测试压缩属性 54 55 //file 56 string fileName = @"D:\\tc2\a.txt"; 57 58 FileStream f = File.Open(fileName, System.IO.FileMode.Open, 59 System.IO.FileAccess.ReadWrite, System.IO.FileShare.None); 60 61 EnableCompression(f.SafeFileHandle); 62 63 f.Close(); 64 65 //dir 66 67 string lpFileName = "D:\\tc2"; 68 69 DirectoryInfo di2 = new DirectoryInfo("D:\\tc2"); 70 71 if ((di2.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed) 72 { 73 SafeFileHandle hDrv = CreateFile(lpFileName, GENERIC_READ | GENERIC_WRITE, 2, IntPtr.Zero, 3, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero); 74 75 EnableCompression(hDrv); 76 } 77 78 Console.Read(); 79 } 80 } 81 } 82
相关链接:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365535(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216(v=vs.85).aspx