C#调用API函数示例

通过调用CreateFile和ReadFile等API函数说明此问题,代码参考MSDN:

http://msdn2.microsoft.com/zh-cn/library/2d9wy99d(vs.80).aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ApiTest
... {
classFileReader
...{
constuintGENERIC_READ=0x80000000;
constuintOPEN_EXISTING=3;
System.IntPtrhandle;

[System.Runtime.InteropServices.DllImport(
"kernel32",SetLastError=true)]
staticexternunsafeSystem.IntPtrCreateFile
(
stringFileName,//filename
uintDesiredAccess,//accessmode
uintShareMode,//sharemode
uintSecurityAttributes,//SecurityAttributes
uintCreationDisposition,//howtocreate
uintFlagsAndAttributes,//fileattributes
inthTemplateFile//handletotemplatefile
);

[System.Runtime.InteropServices.DllImport(
"kernel32",SetLastError=true)]
staticexternunsafeboolReadFile
(
System.IntPtrhFile,
//handletofile
void*pBuffer,//databuffer
intNumberOfBytesToRead,//numberofbytestoread
int*pNumberOfBytesRead,//numberofbytesread
intOverlapped//overlappedbuffer
);

[System.Runtime.InteropServices.DllImport(
"kernel32",SetLastError=true)]
staticexternunsafeboolCloseHandle
(
System.IntPtrhObject
//handletoobject
);

publicboolOpen(stringFileName)
...{
//opentheexistingfileforreading
handle=CreateFile
(
FileName,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0
);

if(handle!=System.IntPtr.Zero)
...{
returntrue;
}

else
...{
returnfalse;
}

}


publicunsafeintRead(byte[]buffer,intindex,intcount)
...{
intn=0;
fixed(byte*p=buffer)
...{
if(!ReadFile(handle,p+index,count,&n,0))
...{
return0;
}

}

returnn;
}


publicboolClose()
...{
returnCloseHandle(handle);
}

}


classProgram
...{
staticintMain(string[]args)
...{
if(args.Length!=1)
...{
System.Console.WriteLine(
"Usage:ReadFile<FileName>");
return1;
}


if(!System.IO.File.Exists(args[0]))
...{
System.Console.WriteLine(
"File"+args[0]+"notfound.");
return1;
}


byte[]buffer=newbyte[128];
FileReaderfr
=newFileReader();

if(fr.Open(args[0]))
...{
//AssumethatanASCIIfileisbeingread.
System.Text.ASCIIEncodingEncoding=newSystem.Text.ASCIIEncoding();

intbytesRead;
do
...{
bytesRead
=fr.Read(buffer,0,buffer.Length);
stringcontent=Encoding.GetString(buffer,0,bytesRead);
System.Console.Write(
"{0}",content);
}

while(bytesRead>0);

fr.Close();
return0;
}

else
...{
System.Console.WriteLine(
"Failedtoopenrequestedfile");
return1;
}


}

}

}

特别要注意的是,由于代码中用到了unsafe代码,因此,编译的时候需要在项目属性中勾选允许编译Unsafe的选项:

否则会报:

Unsafe code may only appear if compiling with /unsafe

的错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值