(精华)2020年9月10日 C#基础知识点 调用动态链接库DLL(调用系统Api和其他语言编写的DLL)
public partial class Program
{<!-- -->
static void FileMethod()
{<!-- -->
//var fs = new FileOpen("d:\\data.txt");//自定义调用
var fs = File.Open("data.txt", FileMode.OpenOrCreate);//系统调用
var bytes = new byte[fs.Length];
var count = (int)fs.Length;
var offset = 0;
while (count > 0)
{<!-- -->
var n = fs.Read(bytes, offset, count);
if (n == 0)
break;
offset += n;
count -= n;
}
}
}
public class FileOpen
{<!-- -->
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
// 使用interop调用CreateFile函数有关CreateFile的详细信息请参阅非托管MSDN参考库
// DllImport调用动态链接库自动寻找windowsAPI kernel32.dll库包含内存管理等
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
private SafeFileHandle _handleValue;
public FileOpen(string path)
{<!-- -->
Load(path);
}
public void Load(string path)
{<!-- -->
if (string.IsNullOrEmpty(path))
{<!-- -->
throw new ArgumentNullException(nameof(path));
}
_handleValue = CreateFile(path, GENERIC_WRITE, 0, IntPtr.Zero, CREATE_ALWAYS, 0, IntPtr.Zero);
if (_handleValue.IsInvalid)
{<!-- -->
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
}