WebClient DownloadFile抛出UnauthorizedAccessException

时间:2018-04-06 16:07:46

标签: c# webclient-download

我想下载一些文件并在%temp%文件夹中执行,但是当我尝试运行它时我得到System.UnauthorizedAccessException

  

ExceçãoSemTratamento:System.Net.WebException:Exceçãoduranteuma   solicitação做WebClient。 ---> System.UnauthorizedAccessException:O   acesso ao caminho'C:\ Users \ Muni \ AppData \ Local \ Temp'foi negado。 EM   System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)
  em System.IO.FileStream.Init(字符串路径,FileMode模式,FileAccess   访问,Int32权限,布尔useRights,FileShare共享,Int32   bufferSize,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,String   msgPath,Boolean bFromProxy,Boolean useLongPath,Boolean checkHost)
  em System.IO.FileStream..ctor(String path,FileMode mode,FileAccess   访问)em System.Net.WebClient.DownloadFile(Uri地址,字符串   fileName)--- Fim do rastreamento de pilhadeexpertçõesinternas---   em System.Net.WebClient.DownloadFile(Uri address,String fileName)
  em System.Net.WebClient.DownloadFile(String address,String fileName)   em encrypt.Program.Main(String [] args)na   C:\ Users \用户穆尼\源\回购\加密\加密\ Program.cs的

         try
        {
            string name = Environment.UserName;
            WebClient Client = new WebClient();
            string temp = "C:\\Users\\" + name + "\\AppData\\Local\\Temp";
            Client.DownloadFile("LINK", temp);
        }
        catch
        {
            return;
        }

1 个答案:

答案 0 :(得分:2)

您没有在路径中提供文件名。

以下是我为测试编写的错误示例:

    string name = Environment.UserName;
    WebClient Client = new WebClient();
    string path = "C:\\";
    Client.DownloadFile("https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", path);

当我运行它时,我得到了同样的例外。

当我在路径中放置文件名时,它可以正常工作。

    string name = Environment.UserName;
    WebClient Client = new WebClient();
    string path = "C:\\test.png";
    Client.DownloadFile("https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", path);

question有一个答案,指出UnauthorizedAccessException例外的原因之一是“路径是目录”。