本文整理汇总了C#中Microsoft.Win32.SafeHandles.SafeFileHandle类的典型用法代码示例。如果您正苦于以下问题:C# SafeFileHandle类的具体用法?C# SafeFileHandle怎么用?C# SafeFileHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SafeFileHandle类属于Microsoft.Win32.SafeHandles命名空间,在下文中一共展示了SafeFileHandle类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.ComponentModel;
class SafeHandlesExample
{
static void Main()
{
try
{
UnmanagedFileLoader loader = new UnmanagedFileLoader("example.xml");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
class UnmanagedFileLoader
{
public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
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;
// Use interop to call the CreateFile function.
// For more information about CreateFile,
// see the unmanaged MSDN reference library.
[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 = null;
public UnmanagedFileLoader(string Path)
{
Load(Path);
}
public void Load(string Path)
{
if (Path == null || Path.Length == 0)
{
throw new ArgumentNullException("Path");
}
// Try to open the file.
handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
// If the handle is invalid,
// get the last Win32 error
// and throw a Win32Exception.
if (handleValue.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
public SafeFileHandle Handle
{
get
{
// If the handle is valid,
// return it.
if (!handleValue.IsInvalid)
{
return handleValue;
}
else
{
return null;
}
}
}
}
开发者ID:.NET开发者,项目名称:Microsoft.Win32.SafeHandles,代码行数:86,代码来源:SafeFileHandle
注:本文中的Microsoft.Win32.SafeHandles.SafeFileHandle类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论