Search Amazon:

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);
Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

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

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms