C# 中的 SafeFileHandle 是什么,我应该在什么时候使用它?

What is SafeFileHandle in C# and when should I use it?

虽然我还在学习System.IO,但在File Stream class的构造函数中,我发现有重载的构造函数类型名为SafeFileHandle,我试着在网上和MSDN Documention上搜索,但我什么也看不懂,我找到了 even stranger 字样,喜欢IntPtr,谁能给我解释一下吗?

public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync);

谁能解释一下,或者有什么好的网站可以学习..?

https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safefilehandle?view=netframework-4.8

http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/clr/src/BCL/Microsoft/Win32/SafeHandles/SafeFileHandle@cs/1/SafeFileHandle@cs

https://csharp.hotexamples.com/examples/-/SafeFileHandle/-/php-safefilehandle-class-examples.html

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=2ahUKEwizlPG3ornlAhVFCKwKHUl9DxIQFjABegQIAxAB&url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fdotnet%2Fapi%2Fmicrosoft.win32.safehandles.safefilehandle.-ctor&usg=AOvVaw3M0YPCVH1439KghalbcDfG

https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream.safefilehandle?view=netframework-4.8

https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safefilehandle?redirectedfrom=MSDN&view=netframework-4.8

这些链接提供有关 SafeFileHandle 的信息,有些链接提供源代码。

你也可以看看这个:How to Close SafeFile Handle properly

IntPtr...

它是一个 "native (platform-specific) size integer." 它在内部表示为 void* 但公开为整数。只要您需要存储非托管指针并且不想使用不安全代码,就可以使用它。 IntPtr.Zero 实际上是 NULL(空指针)。

Pointer...

通常(跨编程语言),指针是表示内存中物理位置的数字。空指针(几乎总是)指向 0,被广泛认为是 "not pointing to anything"。由于系统具有不同数量的支持内存,因此并不总是需要相同数量的字节来保存该数字,因此我们调用一个 "native size integer" 可以在任何特定系统上保存指针的内存。

SafeFileHandle kernel32...

[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);

更多 SafeFileHandlekernel32...

[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
private SafeFileHandle handleValue = null;
handleValue = CreateFile(
Path,
GENERIC_WRITE,
0,
IntPtr.Zero,
OPEN_EXISTING,
0,
IntPtr.Zero);

不过,如果您尝试打开 File,则使用 System.IO Controls

只需打开一个文件并阅读其中的所有文本:

richTextBox1.Text = File.ReadAllText(yourfilename);

您可以将 richTextBox1 更改为您 Control 的名字。

Soft 教授,希望对您有所帮助 :)