[英]Access to the path (..) is denied WPF
在我的應用程序中,我獲得了硬盤的序列號並將其寫入文本文件(如果不存在則創建文件)..這是我的代碼:
string path = @"d:\RegisterKey.txt";
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(GetHDSerialNo);
tw.Close();
文件創建成功,但是TextWriter步驟中發生了問題:
拒絕訪問路徑“ d:\\ RegisterKey.txt”。
試圖以管理員身份運行Visual Studio,但不能解決問題。
任何建議
提前致謝
阿卜杜薩拉姆
您有兩個流打開。 File.Create
創建並返回一個新的流,默認情況下,它不允許共享寫入。 然后,您嘗試使用另一個流對其進行寫入,由於File.Create
的流仍處於打開狀態,因此該流被阻止。 相反,您可以將該流傳StreamWriter
。 像這樣調整代碼:
string path = @"d:\RegisterKey.txt";
using (var stream = File.Create(path))
{
using(TextWriter tw = new StreamWriter(stream))
{
tw.WriteLine(GetHDSerialNo);
}
}
File.Create
方法創建文件並打開FileStream,因此您的文件已經打開。
像這樣走你的流:
var stream = File.Create(path);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.