[英]UnauthorizedAccessException: Access to the path is denied winform
我正在使用FtpWebRequest
從ftp下載我的文件。 但是,當應用程序轉到FileStream
行時,我聲明將其寫出。
以下是我的下載功能:
public void Download(List <string> path)
{
try
{
string timenow = DateTime.Today.Year.ToString() + "_" + DateTime.Today.Month.ToString() + "_" + DateTime.Today.Day.ToString() + "_" + DateTime.Today.Hour.ToString() + "_" + DateTime.Today.Minute.ToString() + "_" + DateTime.Today.Second.ToString();
DirectoryInfo dir = new DirectoryInfo(@"C:\StudySystemFile\" + timenow);
if (!dir.Exists)
dir.Create();
foreach (string p in path)
{
FtpWebRequest request;
request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftp.Hostname + p));
request.Credentials = new System.Net.NetworkCredential(ftp.FtpAccount, ftp.FtpPassword);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = false;
request.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream file = new FileStream(@"C:\StudySystemFile\" + timenow, FileMode.Create, FileAccess.ReadWrite);
byte[] buffer = new byte[1024];
int bytesRead = reader.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
file.Write(buffer, 0, bytesRead);
bytesRead = reader.Read(buffer, 0, buffer.Length);
}
reader.Close();
file.Close();
response.Close();
Console.WriteLine(p);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
運行該程序的用戶無權在C:\\StudySystemFile\\
創建文件,請檢查該文件夾是否存在,並且正在運行該程序的任何用戶都可以在沒有UAC提示的情況下在此處創建文件。
可能發生的情況是,當您使用Create()
創建文件夾時,它正在從C:\\
繼承權限,而C:\\
沒有文件的寫權限,您只會獲得文件夾創建權限。
您需要在程序外部創建文件夾,或者在調用Create()
時需要設置權限 。
您必須獲取UnauthorizedAccessException
。當操作系統由於I / O錯誤或特定類型的安全錯誤而拒絕訪問時引發的異常。
顯然,這是一個許可問題 。
對於Vista / Windows 7/8, C:\\
驅動器被視為系統驅動器,需要您的進程的管理員特權才能直接在其下創建文件。
嘗試以管理員Run Visual Studio as Administrator
運行您的進程或Run Visual Studio as Administrator
,它應該可以工作。
您的應用程序無權寫入該目錄。 您可以通過右鍵單擊您的項目並添加一個新的Application Manifest File
來強制UAC提示。 在此文件中,替換
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
與
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
一個更好的主意是寫到不需要管理員權限的目錄。
您正在使用哪個版本的Framework? 您正在使用哪種安裝/啟動方法? (即clickonce)和建議的其他海報一樣,您是否檢查了C:驅動器上該文件夾的權限? 右鍵單擊該文件夾,然后檢查“安全性”選項卡,確保已登錄的用戶具有對該文件夾的修改以及讀取訪問權限。
如果您只是臨時需要該文件,則考慮將文件寫入IsolatedStorage。 如何在隔離存儲文件中存儲和檢索數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.