![](/img/trans.png)
[英]Question: Using Windows 7, Unauthorized Access Exception when running my application
[英]Unauthorized Access Exception in Windows 7
我有一個應用程序在啟動時讀取許可證文件。 我的安裝在應用程序的Program Files中創建文件夾,創建許可證文件夾並將許可證文件放在那里。 但是,當我嘗試運行該應用程序時,它需要讀取/更新許可證文件。 當我嘗試這樣做時,我得到了“未經授權的訪問例外”。 我以管理員身份登錄,手動運行該程序。
知道為什么即使路徑正確我也無法訪問該文件? 但是在安裝中它創建文件和文件夾就好了嗎?
我有MyApplication.exe,我的許可證閱讀器位於一個名為MyApplicationTools的獨立DLL中。 我正在讀/寫這樣的許可證文件:
//Read
StreamReader reader = new StreamReader(path + "license.lic");
//Write
StreamWriter writer2 = new StreamWriter(path + "License.lic");
string str = Convert.ToBase64String(sharedkey.Key);
writer2.WriteLine(str);
writer2.Close();
謝謝
由於UAC,您的程序沒有獲得管理權限。
右鍵單擊該程序,單擊“以管理員身份運行”,然后重試。
您還可以創建一個清單,告訴Windows始終以管理員身份運行 。
但是,您應該考慮將許可證文件放在用戶的AppData文件夾中,該文件夾不需要管理員權限。
順便說一下,您應該使用Path.Combine
方法來創建路徑。
此外,如果您只想將單個字符串寫入文件,則應調用File.WriteAllText
。
例如:
File.WriteAllText(Path.Combine(path, "License.lic"), Convert.ToBase64String(sharedkey.Key));
請改用AppData。 有一個環境變量。 您可以通過進入資源管理器並輸入%appdata%來查看此信息。 它會帶你到相應的文件夾。 要在C#中訪問它,我編寫了以下函數。
/// <summary>
/// Gets the path where we store Application Data.
/// </summary>
/// <returns>The Application Data path</returns>
public static string GetAppDataPath()
{
string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
dir = System.IO.Path.Combine(dir, "MyCompany\\MyApplication");
System.IO.Directory.CreateDirectory(dir);
return dir;
}
您需要將可寫文件放在用戶應用程序文件夾中 - 普通用戶無法寫入Program Files。 Iirc,在Win7上默認位置是C:\\ Users \\ [用戶名] \\ AppData \\ [appname]。 您不應該以管理員身份運行才能寫入Program Files。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.