为什么下载数据时会出现UnauthorizedAccessException? [英] Why do I get an UnauthorizedAccessException when downloading data?

查看:96
本文介绍了为什么下载数据时会出现UnauthorizedAccessException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码,以便从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:

  • Use the DownloadFile method of WebClient, rather than DownloadData, 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆