You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# FTP下载时报访问路径C:\Users\Administrator\Downloads被拒绝如何解决?

问题核心原因

你的代码尝试将FTP下载的内容直接写入下载文件夹目录本身,而非目录下的具体文件,这是触发访问拒绝错误的直接原因:
代码中 FileStream fs = new FileStream(downloads, FileMode.Create); 传入的 downloads 变量是 C:\Users\Administrator\Downloads 这个文件夹路径,系统不允许把文件夹作为文件对象写入,因此抛出权限拒绝异常。


解决步骤

  1. 先拼接完整的本地保存文件路径
    调用Path.Combine将下载目录和目标文件名拼接为完整的文件路径,同时修正你代码中的变量名拼写错误、语法错误:
    • 你代码中定义的文件名变量是targetFile(大写F),拼接FTP地址时误写为targetfile(小写f),会导致编译错误
    • 变量targetFile定义行末尾缺失分号,需要补全
  2. 权限排查(修改路径后仍报错时检查)
    • 确认程序运行身份对Downloads目录有写入权限,调试阶段可以尝试用管理员身份启动Visual Studio
    • 不要硬编码用户目录路径,保持你当前用SHGetKnownFolderPath获取系统下载目录的逻辑即可,适配不同用户的系统配置
  3. 优化资源释放逻辑
    用using语句包裹非托管资源,不需要手动调用Close()方法,避免异常场景下资源泄露

修正后的核心代码片段

try
{
    string ResponseDescription = "";
    string downloads;
    SHGetKnownFolderPath(KnownFolder.Downloads, 0, IntPtr.Zero, out downloads);

    string UserName = "UserName";
    string Password = "Password";
    string folderName = "folderName";
    string targetFile = "targetfilename"; // 补充分号
    string Server = $"ftp://ip/{folderName}/{targetFile}"; // 修正变量名拼写

    FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(Server);
    req.Method = WebRequestMethods.Ftp.DownloadFile;
    req.Credentials = new NetworkCredential(UserName, Password);
    req.UseBinary = true;
    req.Proxy = null;

    // 拼接本地完整保存路径
    string localSavePath = Path.Combine(downloads, targetFile);
    using (FtpWebResponse response = (FtpWebResponse)req.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (FileStream fs = new FileStream(localSavePath, FileMode.Create))
    {
        byte[] buffer = new byte[2048];
        int ReadCount = stream.Read(buffer, 0, buffer.Length);
        while (ReadCount > 0)
        {
            fs.Write(buffer, 0, ReadCount);
            ReadCount = stream.Read(buffer, 0, buffer.Length);
        }
        ResponseDescription = response.StatusDescription;
    }
}
catch(Exception x)
{
    MessageBox.Show(x.ToString());
}

内容的提问来源于stack exchange,提问作者Alfe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:12:02