Using Windows API from C#

Recently a function in our application stopped working for some reason. We were using the WMI with the .Net Framework 3.5 in C# to determine the amount of freespace on a floppy diskette. For some reason after we upgraded from .Net framework 1.1 and from XP SP2 to XP SP3 the function stopped working. We tried searching alternatives and determining the cause to no avail. Our project lead suggested we attemp to use the Windows API directly instead.

If that were to fail then there would not be much else to do. To our surprise accessing the Windows API worked. Below is the sample code. This is only a sample of how you can still leverage the API directly to work around issues from time to time.




//This is the WindowsApi.cs file
using System;
using System.Runtime.InteropServices;
namespace MAT.Common.Utils
{
public class WindowsApi
{
[DllImport("Kernel32")]
public static extern bool GetDiskFreeSpace(
[MarshalAs(UnmanagedType.LPStr)]string lpRootPathName,
out UInt32 sectorsPerCluster,
out UInt32 bytesPerSector,
out UInt32 numberOfFreeClusters,
out UInt32 totalNmberOfClusters
);
}
}


//This is how we called it from our application

public void Foo()
{
....some code
UInt32 sectorsPerCluster = 0;
UInt32 bytesPerSector = 0;
UInt32 numberOfFreeClusters = 0;
UInt32 totalNumberOfClusters = 0;
var successFul = WindowsApi.GetDiskFreeSpace(drive, out sectorsPerCluster, out bytesPerSector, out numberOfFreeClusters,
out totalNumberOfClusters);

ulong sizeInBytes;
ulong spaceAvailableInBytes;
ulong spaceUsedInBytes;

if(successFul)
{
sizeInBytes= sectorsPerCluster*bytesPerSector*totalNumberOfClusters;
spaceAvailableInBytes = sectorsPerCluster*bytesPerSector*numberOfFreeClusters;
spaceUsedInBytes = sizeInBytes - spaceAvailableInBytes;
}

}

//

Comments

Popular posts from this blog

Simple Example of Using Pipes with C#

Difference Between Adapter and Bridge Design Patterns

Remote Access to Your Home Desktop Using No-IP