C#调用API示例

摘自MSDN,这是一段C#调用Windows系统API函数的示例代码。
在自定义的FileReader类中,导入了CreateFile, ReadFile, CloseHandle三个API函数,并新建了Open,Read,Close方法来应用它们。
在编译时需用unsafe选项,因为用到了C#中所谓的指针
FileReader类在窗体程序、控制台程序、Web程序中皆可使用,不过这只是一个示例,个人可自由发挥,使用其他API,来实现某些“高级”功能。
// readfile.cs
// compile with: /unsafe
// arguments: readfile.cs
 
// Use the program to read and display a text file.
using System;
using System.Runtime.InteropServices;
using System.Text;
 
class FileReader
{
      const uint GENERIC_READ = 0x80000000;
      const uint OPEN_EXISTING = 3;
      IntPtr handle;
 
      [DllImport("kernel32", SetLastError= true)]
      static extern unsafe IntPtr CreateFile(
            string FileName,                    // file name
            uint DesiredAccess,                 // access mode
            uint ShareMode,                     // share mode
            uint SecurityAttributes,            // Security Attributes
            uint CreationDisposition,           // how to create
            uint FlagsAndAttributes,            // file attributes
            int hTemplateFile                   // handle to template file
            );
 
       [DllImport("kernel32", SetLastError= true)]
      static extern unsafe bool ReadFile(
            IntPtr hFile,                       // handle to file
            void* pBuffer,                      // data buffer
            int NumberOfBytesToRead,            // number of bytes to read
            int* pNumberOfBytesRead,            // number of bytes read
            int Overlapped                      // overlapped buffer
            );
 
      [DllImport("kernel32", SetLastError= true)]
      static extern unsafe bool CloseHandle(
            IntPtr hObject   // handle to object
            );
     
      public bool Open( string FileName)
      {
            // open the existing file for reading         
            handle = CreateFile(
                  FileName,
                  GENERIC_READ,
                  0,
                  0,
                  OPEN_EXISTING,
                  0,
                  0);
     
            if (handle != IntPtr.Zero)
                  return true;
            else
                  return false;
      }
 
      public unsafe int Read( byte[] buffer, int index, int count)
      {
            int n = 0;
            fixed ( byte* p = buffer)
            {
                  if (!ReadFile(handle, p + index, count, &n, 0))
                        return 0;
            }
            return n;
      }
 
      public bool Close()
      {
            // close file handle
            return CloseHandle(handle);
      }
}
 
class Test
{
      public static int Main( string[] args)
      {
            if (args.Length != 1)
            {
                  Console.WriteLine("Usage : ReadFile <FileName>");
                  return 1;
            }
           
            if (! System.IO.File.Exists(args[0]))
            {
                  Console.WriteLine("File " + args[0] + " not found.");
                  return 1;
            }
 
            byte[] buffer = new byte[128];
            FileReader fr = new FileReader();
           
            if (fr.Open(args[0]))
            {
                 
                  // Assume that an ASCII file is being read
                  ASCIIEncoding Encoding = new ASCIIEncoding();
                 
                  int bytesRead;
                  do
                  {
                        bytesRead = fr.Read(buffer, 0, buffer.Length);
                        //string content = Encoding.GetString(buffer,0,bytesRead);
                        string content = System.Text.Encoding.Default.GetString(buffer, 0, bytesRead);
                        Console.Write("{0}", content);
                  }
                  while ( bytesRead > 0);
                 
                  fr.Close();
                  return 0;
            }
            else
            {
                  Console.WriteLine("Failed to open requested file");
                  return 1;
            }
      }
}
分享至
一键收藏,随时查看,分享好友!
0人
了这篇文章
类别: 编程技术┆阅读( 0)┆评论( 0) ┆ 返回博主首页┆ 返回博客首页
上一篇 学习“NTFS文件系统”应该从那些方面入手? 下一篇 发明创造-迎合与引导

你可能感兴趣的:(职场,休闲)