c# - FtpWebRequest 下载文件

标签 c# .net ftp ftpwebrequest ftpwebresponse

以下代码旨在通过 FTP 检索文件。但是,我遇到了错误。

serverPath = "ftp://x.x.x.x/tmp/myfile.txt";

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;

request.Method = WebRequestMethods.Ftp.DownloadFile;                
request.Credentials = new NetworkCredential(username, password);

// Read the file from the server & write to destination                
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))            
using (StreamWriter destination = new StreamWriter(destinationFile))
{
    destination.Write(reader.ReadToEnd());
    destination.Flush();
}

错误是:

The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

该文件确实存在于远程机器上,我可以手动执行此 ftp(即我有权限)。谁能告诉我为什么会出现此错误?

最佳答案

我知道这是一篇旧帖子,但我在这里添加以供将来引用。这是我找到的解决方案:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }

根据 Ilya Kogan 的出色建议更新

关于c# - FtpWebRequest 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2781654/

相关文章:

c - 在 C 中通过套接字发送大文件

c# - Linq Complex OrderBy by Props 属性

c# - 如何将一些数据写入excel文件(.xlsx)

c# - 带有进度条 WPF 的异步 Google 文件上传

c# - .NET 反射 : how to get properties defined on partial class

python - 通过 FTP 逐行读取 CSV,而不将整个文件存储在内存/磁盘中

c# - 帮助我找到更好的编程方法

c# - 如何在不使用枚举的情况下设置控件的颜色?

c# - C# 类型上的尾随点表示什么?

python - 使用 urlopen 获取 FTP 服务器上文件的最后修改日期不起作用