gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:49:12 24 4
gpt4 key购买 nike

虽然我还在学习 System.IO,但在 File Stream 类的构造函数中,我发现有重载的构造函数,其类型名为 SafeFileHandle,我尝试在互联网和 MSDN Documention 上搜索,但我什么也看不懂,我发现了甚至 陌生 词,比如 IntPtr ,谁能给我解释一下吗?

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

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

最佳答案

https://learn.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%2Flearn.microsoft.com%2Fen-us%2Fdotnet%2Fapi%2Fmicrosoft.win32.safehandles.safefilehandle.-ctor&usg=AOvVaw3M0YPCVH1439KghalbcDfG

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

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

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

您也可以查看:How to Close SafeFile Handle properly

IntPtr...

这是一个“本地(特定于平台)大小的整数”。它在内部表示为 void* 但显示为整数。只要您需要存储非托管指针并且不想使用不安全代码,就可以使用它。 IntPtr.Zero 实际上是 NULL(空指针)。

指针...

通常(跨编程语言),指针是表示内存中物理位置的数字。空指针(几乎总是)指向 0,并且被广泛认为是“不指向任何东西”。由于系统具有不同数量的支持内存,因此并不总是需要相同数量的字节来保存该数字,因此我们称其为“ native 大小整数”,它可以保存任何特定系统上的指针。

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

不过,如果您尝试打开一个文件,则使用System.IO Controls

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

richTextBox1.Text = File.ReadAllText(你的文件名);

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

我希望我能帮到你,Soft 教授 :)

关于c# - C# 中的 SafeFileHandle 是什么,我应该在什么时候使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58568415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com