6
6
7
7
class SafeHandlesExample
8
8
{
9
-
10
9
static void Main ( )
11
10
{
12
11
try
13
12
{
14
-
15
13
UnmanagedFileLoader loader = new UnmanagedFileLoader ( "example.xml" ) ;
16
14
}
17
15
catch ( Exception e )
@@ -24,7 +22,6 @@ static void Main()
24
22
25
23
class UnmanagedFileLoader
26
24
{
27
-
28
25
public const short FILE_ATTRIBUTE_NORMAL = 0x80 ;
29
26
public const short INVALID_HANDLE_VALUE = - 1 ;
30
27
public const uint GENERIC_READ = 0x80000000 ;
@@ -36,52 +33,40 @@ class UnmanagedFileLoader
36
33
// Use interop to call the CreateFile function.
37
34
// For more information about CreateFile,
38
35
// see the unmanaged MSDN reference library.
39
- [ DllImport ( "kernel32.dll" , SetLastError = true , CharSet = CharSet . Unicode ) ]
36
+ [ DllImport ( "kernel32.dll" , SetLastError = true , CharSet = CharSet . Unicode ) ]
40
37
static extern SafeFileHandle CreateFile ( string lpFileName , uint dwDesiredAccess ,
41
38
uint dwShareMode , IntPtr lpSecurityAttributes , uint dwCreationDisposition ,
42
39
uint dwFlagsAndAttributes , IntPtr hTemplateFile ) ;
43
40
44
41
private SafeFileHandle handleValue = null ;
45
42
46
- public UnmanagedFileLoader ( string Path )
47
- {
48
- Load ( Path ) ;
49
- }
43
+ public UnmanagedFileLoader ( string path )
44
+ => Load ( path ) ;
50
45
51
- public void Load ( string Path )
46
+ public void Load ( string path )
52
47
{
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 ) ) ;
57
50
58
51
// 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 ) ;
60
53
61
54
// If the handle is invalid,
62
55
// get the last Win32 error
63
56
// and throw a Win32Exception.
64
57
if ( handleValue . IsInvalid )
65
- {
66
58
Marshal . ThrowExceptionForHR ( Marshal . GetHRForLastWin32Error ( ) ) ;
67
- }
68
59
}
69
60
70
61
public SafeFileHandle Handle
71
62
{
72
63
get
73
64
{
74
- // If the handle is valid,
75
- // return it.
76
65
if ( ! handleValue . IsInvalid )
77
- {
78
66
return handleValue ;
79
- }
80
- else
81
- {
82
- return null ;
83
- }
67
+
68
+ return null ;
84
69
}
85
70
}
86
71
}
87
- //</Snippet1>
72
+ //</Snippet1>
0 commit comments