为什么下载数据时会出现UnauthorizedAccessException? [英] Why do I get an UnauthorizedAccessException when downloading data?
问题描述
我编写了这段代码,以便从FTP服务器下载文件.当程序尝试下载并保存文件时,出现访问被拒绝错误.我尝试使用管理员权限打开该程序,但它给出了相同的错误.
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!");
推荐答案
您需要在对File.Create
的调用中提供完整的文件路径.现在,您正在尝试使用要下载的文件覆盖游戏"目录,这是不好的.
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.
尝试将downloadTo
设置为类似C:\Users\agam\Desktop\Games\myfile.ext
的名称,而不是设置为现在的C:\Users\agam\Desktop\Games\
.
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:
- 使用
WebClient
的DownloadFile
方法,而不是DownloadData
,以节省您一些精力. - 在
using
调用以确保即使您的方法遇到异常,它也已关闭.否则,您可能会冒客户所拥有的资源泄漏的风险.
- Use the
DownloadFile
method ofWebClient
, 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.
例如:
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(txtFTPuser.Text,
txtFTPpassword.Text);
request.DownloadFile(fullDownloadPath, downloadTo);
MessageBox.Show("Completed!");
}
这篇关于为什么下载数据时会出现UnauthorizedAccessException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!