调用系统DLL,可以做许多事,例如读取电脑一些基本信息,如硬盘序列号,mac地址等内存信息等,
public classWin32API
{
[DllImport("NETAPI32.DLL")]
public static extern char Netbios(refNCB ncb);
}
public string GetMacAddress()
{
string addr = "";
try
{
int cb;
ASTAT adapter;
NCB Ncb = new NCB();
char uRetCode;
LANA_ENUM lenum;
Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
cb = Marshal.SizeOf(typeof(LANA_ENUM));
Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
Ncb.ncb_length = (ushort)cb;
uRetCode = Win32API.Netbios(ref Ncb);
lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer,typeof(LANA_ENUM));
Marshal.FreeHGlobal(Ncb.ncb_buffer);
if (uRetCode != (short)NCBCONST.NRC_GOODRET)
return "";
for (int i = 0; i < lenum.length; i++)
{
Ncb.ncb_command = (byte)NCBCONST.NCBRESET;
Ncb.ncb_lana_num = lenum.lana[i];
uRetCode = Win32API.Netbios(ref Ncb);
if (uRetCode != (short)NCBCONST.NRC_GOODRET)
return "";
Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;
Ncb.ncb_lana_num = lenum.lana[i];
Ncb.ncb_callname[0] = (byte)'*';
cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) +Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF;
Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
Ncb.ncb_length = (ushort)cb;
uRetCode = Win32API.Netbios(ref Ncb);
adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer,typeof(ADAPTER_STATUS));
Marshal.FreeHGlobal(Ncb.ncb_buffer);
if (uRetCode == (short)NCBCONST.NRC_GOODRET)
{
if (i > 0)
addr += ":";
addr = string.Format("{0,2:X}{1,2:X}{2,2:X}{3,2:X}{4,2:X}{5,2:X}",
adapter.adapt.adapter_address[0],
adapter.adapt.adapter_address[1],
adapter.adapt.adapter_address[2],
adapter.adapt.adapter_address[3],
adapter.adapt.adapter_address[4],
adapter.adapt.adapter_address[5]);
}
}
}
catch
{ }
return addr.Replace(' ','0');
}
[DllImport("kernel32.dll")]
private static extern int GetVolumeInformation
(
string lpRootPathName,
string lpVolumeNameBuffer,
int nVolumeNameSize,
ref int lpVolumeSerialNumber,
int lpMaximumComponentLength,
int lpFileSystemFlags,
string lpFileSystemNameBuffer,
int nFileSystemNameSize
);
///<summary>
/// C盘序列号
///</summary>
///<param name=""></param>
///<returns></returns>
public static string HDVal()
{
const int MAX_FILENAME_LEN = 256;
int retVal = 0;
int a = 0;
int b = 0;
string str1 = null;
string str2 = null;
int i = GetVolumeInformation(
"c:\\",
str1,
MAX_FILENAME_LEN,
ref retVal,
a,
b,
str2,
MAX_FILENAME_LEN
);
return retVal.ToString();
}
下面是一个真实案例,获取asp.net网站的内存信息
[DllImport("kernel32")]
public staticextern void GlobalMemoryStatus(refMEMORY_INFO meminfo);
//定义内存的信息结构
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_INFO
{
public uint dwLength;
public uint dwMemoryLoad;
public uint dwTotalPhys;
public uint dwAvailPhys;
public uint dwTotalPageFile;
public uint dwAvailPageFile;
public uint dwTotalVirtual;
public uint dwAvailVirtual;
}
serversoft.Text = Request.ServerVariables["server_software"];
servernet.Text = Environment.Version.Major +"." + Environment.Version.Minor +"." + Environment.Version.Build +"." + Environment.Version.Revision;
serverhttps.Text = Request.ServerVariables["HTTPS"];
serverport.Text = Request.ServerVariables["server_port"];
serverout.Text = Server.ScriptTimeout.ToString();
servertime.Text = DateTime.Now.ToString();
serverarea.Text = (DateTime.Now -DateTime.UtcNow).TotalHours > 0 ? "+" + (DateTime.Now - DateTime.UtcNow).TotalHours.ToString() : (DateTime.Now -DateTime.UtcNow).TotalHours.ToString();
try
{
aspnetn.Text = (System.Diagnostics.Process.GetCurrentProcess().WorkingSet / 1048576).ToString("N2") +" MB";
}
catch
{
aspnetn.Text = "系统拒绝提供。";
}
try
{
aspnetcpu.Text = (System.Diagnostics.Process.GetCurrentProcess().TotalProcessorTime).TotalSeconds.ToString("N0") +" 秒";
}
catch
{
aspnetcpu.Text = "系统拒绝提供。";
}
serverstart.Text = (System.Environment.TickCount / 3600000).ToString("N2");
try
{
prstart.Text = System.Diagnostics.Process.GetCurrentProcess().StartTime.ToString();
}
catch
{
prstart.Text = "系统拒绝提供。";
}
cpuc.Text = Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS");
cputype.Text = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER");
//调用GlobalMemoryStatus函数获取内存的相关信息
MEMORY_INFO MemInfo;
MemInfo = new MEMORY_INFO();
GlobalMemoryStatus(ref MemInfo);
LbdwMemoryLoad.Text = MemInfo.dwMemoryLoad + " %";
LbdwTotalPhys.Text = dFileSize(MemInfo.dwTotalPhys);
LbdwAvailPhys.Text = dFileSize(MemInfo.dwAvailPhys);
LbdwTotalPageFile.Text = dFileSize(MemInfo.dwTotalPageFile);
LbdwAvailPageFile.Text = dFileSize(MemInfo.dwAvailPageFile);
LbdwTotalVirtual.Text = dFileSize(MemInfo.dwTotalVirtual);
下面例子是调用deplic做的dll,它提供接口供我们使用.
protected void Application_Start(object sender, EventArgs e)
{
MT4ApiFuns.LoadLib();//加载mt4组件
}
///<summary>
/// MT4ApiFuns客户端接口方法
///请在网站一级目录下建立Global.asax文件,并在文件内输入内容如下:
///小于号%@ Application Inherits="MT4Api.Global" Language="C#" %大于号
///</summary>
public class MT4ApiFuns
{
public static int GetDateTimeInt(DateTime dt)
{
int intResult = 0;
System.DateTime startTime =TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (int)(DateTime.Now - startTime).TotalSeconds;
return intResult;
}
public static int CreateInterface()
{
DCreateInterface temp = (DCreateInterface)GetAddress(instance,"CreateInterface", typeof(DCreateInterface));
return Convert.ToInt16(temp());
}
public static int Connect(string str)
{
DConnect temp = (DConnect)GetAddress(instance,"Connect", typeof(DConnect));
return Convert.ToInt16(temp(str));
}
public static int Login(int i,string strPwd)
{
DLogin temp = (DLogin)GetAddress(instance,"Login", typeof(DLogin));
return Convert.ToInt16(temp(i, strPwd));
}
///使用客户端登录
public static int ClientLogin(int i,string strPwd)
{
DLogin temp = (DLogin)GetAddress(instance,"ClientLogin", typeof(DLogin));
return Convert.ToInt16(temp(i, strPwd));
}
//判断零持仓(-1为出错,大于0为有持仓,0为零持仓)
public static int GetZeroTrades(int userNO)
{
ZeroTrade temp = (ZeroTrade)GetAddress(instance,"GetTrades", typeof(ZeroTrade));
return Convert.ToInt16(temp(userNO));
}
public static int NewRecord(refUserRecord user)
{
DNewRecord temp = (DNewRecord)GetAddress(instance,"UserRecordNew", typeof(DNewRecord));
return Convert.ToInt16(temp(ref user));
}
public static int UserRecordUpdate(refUserRecord user)
{
DUserRecordUpdate temp = (DUserRecordUpdate)GetAddress(instance,"UserRecordUpdate", typeof(DUserRecordUpdate));
return Convert.ToInt16(temp(ref user));
}
public static int AddBalance(int userNO,Double dbBalance,outint num)
{
DAddBalance temp = (DAddBalance)GetAddress(instance,"AddBalance", typeof(DAddBalance));
return Convert.ToInt16(temp(userNO, dbBalance,out num));
}
public static int GetMarginFree(int intLogin,out double dbBalance)
{
DGetMarginFree temp = (DGetMarginFree)GetAddress(instance,"GetMarginFree", typeof(DGetMarginFree));
return Convert.ToInt16(temp(intLogin, out dbBalance));
}
public static int SetUserPassword(int intLogin,int intIsInvestor, int intClearPubkey,char[] password)
{
DSetUserPassword temp = (DSetUserPassword)GetAddress(instance,"SetUserPassword", typeof(DSetUserPassword));
return Convert.ToInt16(temp(intLogin, intIsInvestor, intClearPubkey, password));
}
static private IntPtr instance;
//要加载方法的委托
delegate int DConnect(string str);
delegate int DCreateInterface();
delegate int DLogin(int userNO,string strPwd);
delegate int DNewRecord(refUserRecord user);
delegate int DUserRecordUpdate(refUserRecord user);
//mt4ID,金额,入金方式,订号
delegate int DAddBalance(int userNO,double dbBalance,outint num);
delegate int ZeroTrade(int userNO);
delegate int DGetMarginFree(int intLogin,out double dbBalance);
delegate int DSetUserPassword(int intLogin,int intIsInvestor, int intClearPubkey,char[] password);
//导入引擎dll
[DllImport("Kernel32.dll")]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("Kernel32.dll", SetLastError =true)]
public static extern int GetProcAddress(
IntPtr hModule, string lpProcName);
[DllImport("Kernel32.dll", EntryPoint ="FreeLibrary", SetLastError = true)]
public static extern bool FreeLibrary(IntPtr hModule);
//获取方法指针
static private Delegate GetAddress(IntPtr dllModule,string functionname, Type t)
{
int addr = GetProcAddress(instance, functionname);
if (addr == 0)
return null;
else
return Marshal.GetDelegateForFunctionPointer(new IntPtr(addr), t);
}
//加载DLL
public static void LoadLib()
{
instance = LoadLibrary(HttpContext.Current.Server.MapPath("~/bin/mt4/MT4ManAPI.dll"));
if (instance.ToInt32() == 0)
{
instance = LoadLibrary(HttpContext.Current.Server.MapPath("~/bin/mt4/MT4ManAPI.dll"));
if (instance.ToInt32() == 0)
{
HttpContext.Current.Response.Write("MT4ManAPI.dll文件路径错误,请将其放置在bin/mt4/目录下!");
HttpContext.Current.Response.End();
}
}
}
///<summary>
///卸载DLL
///</summary>
public static void FreeLib()
{
FreeLibrary(instance);
}
}