问题
I wrote this code to download a file from an FTP server. When the program tries to download and save the file, I get an access denied error. I tried opening the program with admin rights, but it gives the same error.
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(txtFTPuser.Text,
txtFTPpassword.Text);
/*List all directory files*/
byte[] fileData = request.DownloadData(fullDownloaPath);//dnoces.dreamhost.com
FileStream fi = File.Create(downloadTo);
fi.Write(fileData, 0, fileData.Length);
fi.Close();
MessageBox.Show("Completed!");
回答1:
You need to provide the full file path in your call to File.Create
. Right now, you're trying to overwrite your "Games" directory with the file you're downloading, and that's no good.
Try setting downloadTo
to something like C:\Users\agam\Desktop\Games\myfile.ext
instead of, as it's likely set to now, C:\Users\agam\Desktop\Games\
.
As an aside, there are two obvious improvements to your code I'd encourage you to look at:
- Use the DownloadFile method of
WebClient
, rather thanDownloadData
, to save you some effort. - Wrap the creation of your WebClient in a using call to ensure that it's closed even if your method encounters an exception. Otherwise, you risk a leak of resources held by the client.
For example:
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(txtFTPuser.Text,
txtFTPpassword.Text);
request.DownloadFile(fullDownloadPath, downloadTo);
MessageBox.Show("Completed!");
}
回答2:
What is the value of "downloadTo" when the file create is called? If "download to" is the games directory rather than the full path of that target file, you'd probably get that error message, since you'd be trying to overwrite a (probably open) directory with a file.
回答3:
you will need to do two things, if you are running it from visual studio, try opening visual studio as Administrator, or add the current user with elevated rights.
来源:https://stackoverflow.com/questions/7715397/why-do-i-get-an-unauthorizedaccessexception-when-downloading-data