首页 > 开发 > 综合 > 正文

Get Volume Serial Number in C#

2024-07-21 02:22:11
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表