Invoke NTFS file compression from C#

Windows PC's using NTFS (NT File System) store files in a compressed format. Unfortunately in .NET there is no intrinsic way using the System.IO namespace to compress files.

You can, however, invoke the NTFS functionality to compress a file. While this requires only a few lines of code the resultant file is not compressed nearly as much as it would be if you had used WinZip or some other tool. For an example on how to zip a file in .NET, click here.

Anyway, here is the C# code:

    
    using System.IO;
    using System.Runtime.InteropServices;

    [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);

    string fileName = @"C:\Temp\test.mdb";
    int lpBytesReturned = 0;
    int FSCTL_SET_COMPRESSION = 0x9C040;
    short COMPRESSION_FORMAT_DEFAULT = 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,
        ref COMPRESSION_FORMAT_DEFAULT, 2 /*sizeof(short)*/, IntPtr.Zero, 0,
        ref lpBytesReturned, IntPtr.Zero);

About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2016 TheScarms
Goto top of page