[英]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://csharp.hotexamples.com/examples/-/SafeFileHandle/-/php-safefilehandle-class-examples.html
這些鏈接提供有關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);
SafeFileHandle
和kernel32
的更多內容...
[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.