C# FTP下载时报访问路径C:\Users\Administrator\Downloads被拒绝如何解决?
问题核心原因
你的代码尝试将FTP下载的内容直接写入下载文件夹目录本身,而非目录下的具体文件,这是触发访问拒绝错误的直接原因:
代码中 FileStream fs = new FileStream(downloads, FileMode.Create); 传入的 downloads 变量是 C:\Users\Administrator\Downloads 这个文件夹路径,系统不允许把文件夹作为文件对象写入,因此抛出权限拒绝异常。
解决步骤
- 先拼接完整的本地保存文件路径
调用Path.Combine将下载目录和目标文件名拼接为完整的文件路径,同时修正你代码中的变量名拼写错误、语法错误:- 你代码中定义的文件名变量是
targetFile(大写F),拼接FTP地址时误写为targetfile(小写f),会导致编译错误 - 变量
targetFile定义行末尾缺失分号,需要补全
- 你代码中定义的文件名变量是
- 权限排查(修改路径后仍报错时检查)
- 确认程序运行身份对Downloads目录有写入权限,调试阶段可以尝试用管理员身份启动Visual Studio
- 不要硬编码用户目录路径,保持你当前用
SHGetKnownFolderPath获取系统下载目录的逻辑即可,适配不同用户的系统配置
- 优化资源释放逻辑
用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
相关产品推荐
相关产品推荐

