簡體   English   中英

c# 中的 SafeFileHandle 是什么,我應該什么時候使用?

[英]What is SafeFileHandle in c# and when should i use?

While I am still learning System.IO, in File Stream class 's constructors, I found that there are overloaded constructors with the type named SafeFileHandle , I tried to search on the internet and the MSDN Documention, but I can't understand anything,我發現了更奇怪的詞,比如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%2Fen-us%2Fdocs.microsoft.com 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的信息,有些提供源代碼。

您還可以查看: 如何正確關閉 SafeFile 句柄

IntPtr ...

這是一個“本機(特定於平台)大小的 integer”。 它在內部表示為 void*,但公開為 integer。 您可以在需要存儲非托管指針並且不想使用不安全代碼時使用它。 IntPtr.Zero 實際上是 NULL(一個 null 指針)。

Pointer ...

通常(跨編程語言),指針是一個數字,表示 memory 中的物理位置。 null 指針(幾乎總是)指向 0,並被廣泛認為“不指向任何東西”。 由於系統支持的 memory 數量不同,因此保存該數字並不總是需要相同數量的字節,因此我們將其稱為“本機大小整數”,它可以保存任何特定系統上的指針。

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 教授:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM