我期望这段代码:
if (!File.Exists(fullFileName))
{
File.Create(fullFileName);
}
File.SetAttributes(fullFileName, FileAttributes.Compressed);
要设置这个标志:
但它没有...我做错了什么?如何在文件上设置该标志?
更新:它说 in the documentation
"It is not possible to change the compression status of a File object using the SetAttributes method."
而且显然它在使用静态 File.SetAttributes 时也不起作用。
鉴于此,如何实现这一点?
最佳答案
您可以使用 p/invoke 来压缩文件。
我给自己做了一个静态辅助函数:
public static class FileTools
{
private const int FSCTL_SET_COMPRESSION = 0x9C040;
private const short COMPRESSION_FORMAT_DEFAULT = 1;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int DeviceIoControl(
IntPtr hDevice,
int dwIoControlCode,
ref short lpInBuffer,
int nInBufferSize,
IntPtr lpOutBuffer,
int nOutBufferSize,
ref int lpBytesReturned,
IntPtr lpOverlapped);
public static bool EnableCompression(IntPtr 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;
}
}
例如,我在代码中使用文件名:
using (var fileToCompress = File.Open(fileNameToCompress, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
FileTools.EnableCompression(fileToCompress.Handle);
关于c# - 设置文件压缩属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31032834/