Skip to content

Commit 885dc23

Browse files
authored
Update sample.cs (#8740)
1 parent 107a574 commit 885dc23

File tree

1 file changed

+10
-25
lines changed
  • snippets/csharp/Microsoft.Win32.SafeHandles/SafeFileHandle/Overview

1 file changed

+10
-25
lines changed

snippets/csharp/Microsoft.Win32.SafeHandles/SafeFileHandle/Overview/sample.cs

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@
66

77
class SafeHandlesExample
88
{
9-
109
static void Main()
1110
{
1211
try
1312
{
14-
1513
UnmanagedFileLoader loader = new UnmanagedFileLoader("example.xml");
1614
}
1715
catch (Exception e)
@@ -24,7 +22,6 @@ static void Main()
2422

2523
class UnmanagedFileLoader
2624
{
27-
2825
public const short FILE_ATTRIBUTE_NORMAL = 0x80;
2926
public const short INVALID_HANDLE_VALUE = -1;
3027
public const uint GENERIC_READ = 0x80000000;
@@ -36,52 +33,40 @@ class UnmanagedFileLoader
3633
// Use interop to call the CreateFile function.
3734
// For more information about CreateFile,
3835
// see the unmanaged MSDN reference library.
39-
[DllImport("kernel32.dll", SetLastError = true, CharSet=CharSet.Unicode)]
36+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
4037
static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
4138
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
4239
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
4340

4441
private SafeFileHandle handleValue = null;
4542

46-
public UnmanagedFileLoader(string Path)
47-
{
48-
Load(Path);
49-
}
43+
public UnmanagedFileLoader(string path)
44+
=> Load(path);
5045

51-
public void Load(string Path)
46+
public void Load(string path)
5247
{
53-
if (Path == null || Path.Length == 0)
54-
{
55-
throw new ArgumentNullException("Path");
56-
}
48+
if (path == null || path.Length == 0)
49+
throw new ArgumentNullException(nameof(path));
5750

5851
// Try to open the file.
59-
handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
52+
handleValue = CreateFile(path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
6053

6154
// If the handle is invalid,
6255
// get the last Win32 error
6356
// and throw a Win32Exception.
6457
if (handleValue.IsInvalid)
65-
{
6658
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
67-
}
6859
}
6960

7061
public SafeFileHandle Handle
7162
{
7263
get
7364
{
74-
// If the handle is valid,
75-
// return it.
7665
if (!handleValue.IsInvalid)
77-
{
7866
return handleValue;
79-
}
80-
else
81-
{
82-
return null;
83-
}
67+
68+
return null;
8469
}
8570
}
8671
}
87-
//</Snippet1>
72+
//</Snippet1>

0 commit comments

Comments
 (0)