新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:Get Volume Serial Number in C#

Get Volume Serial Number in C#

新客网 XKER.COM 2003-07-12 来源: 收藏本文
Recently somebody asked how to get the Hard Drive serial number in VB.NET. The easy answer of course is to use VBScript with the WMI classes. Actually, this gets the "Volume" serial number, not the hard-coded manufacturer's hard drive serial number, which needs to be retrieved with custom software that can vary by drive manufacturer. The "Volume" serial number is created when you format a drive, and it can be changed without reformatting, although in practice people rarely do so.

I thought it might be a good experiment to try and do this using the native Windows API "GetVolumeInformation" instead, which requires P/Invoke, in C#. This can be useful information for software and control developers as it can be used to verify licensing for a single computer. For example, on installation we could read the Volume Serial Number of the user's C: drive in our Internet registration module, and have it submit this to a webservice which uses the number as the encryption key for a valid license key to "unlock" the product, which would then be stored in the registry. If somebody attempted to install a single - computer license product on another machine, the key would be invalidated.

The important issue with many of the API's is that you have to get the parameter types correct for them to work with P/Invoke from managed code.

With "GetVolumeInformation", the signature looks as follows:

[DllImport("kernel32.dll")]
private static extern long GetVolumeInformation(string PathName, StringBuilder VolumeNameBuffer, UInt32 VolumeNameSize, ref UInt32 VolumeSerialNumber, ref UInt32 MaximumComponentLength, ref UInt32 FileSystemFlags, StringBuilder FileSystemNameBuffer, UInt32 FileSystemNameSize);

Note that some of the parameters that you would think would be of type "int" must be passed as "UInt32", which corresponds to the .NET type "uint", and oftentimes a string must be passed as StringBuilder.

The actual method , with a string return value for convenience, looks like this:

public string GetVolumeSerial(string strDriveLetter)
{
uint serNum = 0;
uint maxCompLen = 0;
StringBuilder VolLabel = new StringBuilder(256); // Label
UInt32 VolFlags = new UInt32();
StringBuilder FSName = new StringBuilder(256); // File System Name
strDriveLetter+=":\\"; // fix up the passed-in drive letter for the API call
long Ret = GetVolumeInformation(strDriveLetter, VolLabel, (UInt32)VolLabel.Capacity, ref serNum, ref maxCompLen, ref VolFlags, FSName, (UInt32)FSName.Capacity);

return Convert.ToString(serNum);
}

收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐