尔冬橙

博客园 首页 新随笔 联系 订阅 管理

C#中可以调用Windows API函数,其实也可以使用其他DLL中的函数。同时,C#中可以使用指针等非安全的代码,虽然用得少,但有时候还是会遇到必须要用的时候。

所以了解C#中如何使用指针还是有必要的。

此示例演示如何使用API函数实现读文件,代码如下:

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

namespace ConsoleApplication13
{
    using System.Runtime.InteropServices;
    class APIFileReader
    {
        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe int CreateFile(
            string fileName,            
            uint desiredAccess,
            uint shareMode,
            uint attributes,
            uint creationDisposition,
            uint flagsAndAttributes,
            uint templateFile
            );
        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe bool ReadFile(
            int hFile,
            void * lpBuffer,
            int nBytesToRead,
            int * nBytesRead,
            int overlapped
            );
        //构造方法打开已有文件,并设置文件句柄的成员
        public APIFileReader(string fileName)
        {
            fileHandle = CreateFile(
                fileName,//文件名
                GenericRead,//所需访问方式
                UseDefault,//共享模式
                UseDefault,//属性
                OpenExisting,//创建目的
                UseDefault,//标志与属性
                UseDefault//模版文件
                );
        }
        public unsafe int Read(byte[] buffer, int index, int count)
        {
            int byteRead = 0;
            fixed (byte* bytePointer = buffer)
            {
                ReadFile(
                    fileHandle,                 //文件句柄
                    bytePointer + index,        //缓冲区指针
                    count,                      //要读取的字节数
                    &byteRead,                  //已读入字节数
                    0                           //交叠
                    );
            }
            return byteRead;
        }
        const uint GenericRead = 0x80000000;
        const uint OpenExisting = 3;
        const uint UseDefault = 0;
        int fileHandle;
    }
    class Test
    {
        static void Main(string[] args)
        {
            //传入一个已有的文件的名字
            APIFileReader fileReader = new APIFileReader(@"c:\hello.txt");
            //创建缓冲
            const int BuffSize = 1024*8;
            byte[] buffer = new byte[BuffSize];
            //ASCIIEncoding asciiEncoder = new ASCIIEncoding();
            //将文件读入到缓冲并输出到控制台
            while (fileReader.Read(buffer, 0, BuffSize) != 0)
            {
                //Console.WriteLine("{0}", asciiEncoder.GetString(buffer));
                Console.WriteLine("{0}", Encoding.GetEncoding("gb2312").GetString(buffer));
            }
            Console.ReadLine();
        }
    }
}

 

posted on 2012-07-26 22:44  尔冬橙  阅读(297)  评论(0编辑  收藏  举报