Skip to content

Commit

Permalink
Update sample.cs (#8740)
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharylayne committed Jun 5, 2024
1 parent 107a574 commit 885dc23
Showing 1 changed file with 10 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@

class SafeHandlesExample
{

static void Main()
{
try
{

UnmanagedFileLoader loader = new UnmanagedFileLoader("example.xml");
}
catch (Exception e)
Expand All @@ -24,7 +22,6 @@ static void Main()

class UnmanagedFileLoader
{

public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
public const uint GENERIC_READ = 0x80000000;
Expand All @@ -36,52 +33,40 @@ class UnmanagedFileLoader
// 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)]
[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 UnmanagedFileLoader(string path)
=> Load(path);

public void Load(string Path)
public void Load(string path)
{
if (Path == null || Path.Length == 0)
{
throw new ArgumentNullException("Path");
}
if (path == null || path.Length == 0)
throw new ArgumentNullException(nameof(path));

// Try to open the file.
handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
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;
}

return null;
}
}
}
//</Snippet1>
//</Snippet1>

0 comments on commit 885dc23

Please sign in to comment.