DeviceIoControl to compress files

J

Jules Crown

Everyone,

greetings, newbee here. What I'm trying to do is to compress files on NTFS
from C#.
I've been fishing around for info and gathered the hereafter. I'd like to
know what's wrong with it.

[DllImport("kernel32.dll")]
public static extern int DeviceIoControl(
IntPtr hDevice,
[MarshalAs(UnmanagedType.U4)] int dwIoControlCode,
IntPtr lpInBuffer,
[MarshalAs(UnmanagedType.U4)] int nInBufferSize,
IntPtr lpOutBuffer,
[MarshalAs(UnmanagedType.U4)] int nOutBufferSize,
[MarshalAs(UnmanagedType.U4)] ref int lpBytesReturned,
IntPtr lpOverlapped);

private static int FSCTL_SET_COMPRESSION = 0x9C040;
private static IntPtr COMPRESSION_FORMAT_DEFAULT = new IntPtr(1);

FileStream f = File.Open(fileName, System.IO.FileMode.Open,
System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)

int result = DeviceIoControl(f.Handle, FSCTL_SET_COMPRESSION,
COMPRESSION_FORMAT_DEFAULT, IntPtr.Size, IntPtr.Zero, 0, ref
lpBytesReturned, IntPtr.Zero);

It compiles, it even runs, but the file is not compressed, and result = 0.
Any ideas? Many thanks,
Jules
 
M

Mattias Sjögren

Jules,

You're currently passing a pointer with the value 1 to the lpInBuffer
parameter. If I read the docs right, you should be passing a pointer
to a short containing the value 1 instead. So try to change the
declaration to

[DllImport("kernel32.dll")]
public static extern int DeviceIoControl(IntPtr hDevice, int
dwIoControlCode, ref short lpInBuffer, int nInBufferSize, IntPtr
lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr
lpOverlapped);

And theen call it like this

short COMPRESSION_FORMAT_DEFAULT = 1;

int result = DeviceIoControl(f.Handle, FSCTL_SET_COMPRESSION,
ref COMPRESSION_FORMAT_DEFAULT, 2 /*sizeof(short)*/, IntPtr.Zero, 0,
ref lpBytesReturned, IntPtr.Zero);



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top