41

以下代码旨在通过 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();
}

错误是:

远程服务器返回错误:(550)文件不可用(例如,找不到文件,无法访问)

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

4

8 回答 8

53

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

    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 的出色建议更新

于 2011-09-23T23:35:32.040 回答
33

最简单的方法

使用 .NET 框架从 FTP 服务器下载二进制文件的最简单方法是使用WebClient.DownloadFile

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

高级选项

FtpWebRequest仅当您需要更大的控制时才使用WebClient不提供的(如TLS/SSL 加密、进度监控、ascii/文本传输模式、恢复传输等)。简单的方法是将 FTP 响应流复制到FileStream使用Stream.CopyTo

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

进度监控

如果您需要监控下载进度,您必须自己按块复制内容:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

有关 GUI 进度 (WinForms ProgressBar),请参阅:
FtpWebRequest FTP 下载与 ProgressBar


下载文件夹

如果要从远程文件夹下载所有文件,请参阅
C# 通过 FTP 下载所有文件和子目录

于 2017-06-28T05:49:08.170 回答
26

您可能会对FptWebRequest 类参考中的这一段感兴趣:

URI 可以是相对的或绝对的。如果 URI 的格式为“ ftp://contoso.com/%2fpath”(%2f是转义的“/”),则 URI 是绝对的,当前目录是 /path。但是,如果 URI 的格式为“ ftp://contoso.com/path ”,则 .NET Framework 首先登录 FTP 服务器(使用 Credentials 属性设置的用户名和密码),然后登录当前目录设置为/路径。

于 2010-05-06T14:20:59.253 回答
2

我遇到过同样的问题!

我的解决方案是将public_html文件夹插入下载 URL。

服务器上的真实文件位置:

myhost.com/public_html/myimages/image.png

网址:

www.myhost.com/myimages/image.png

于 2012-07-10T09:54:02.837 回答
2
    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

我希望它可以帮助你。

于 2016-11-10T05:10:33.127 回答
1
   public void download(string remoteFile, string localFile)
    {
       private string host = "yourhost";
       private string user = "username";
       private string pass = "passwd";
       private FtpWebRequest ftpRequest = null;
       private FtpWebResponse ftpResponse = null;
       private Stream ftpStream = null;
       private int bufferSize = 2048;

        try
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            ftpStream = ftpResponse.GetResponseStream();

            FileStream localFileStream = new FileStream(localFile, FileMode.Create);

            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

            try
            {
                while (bytesRead > 0)
                {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                }
            }

            catch (Exception) {  }

            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }

        catch (Exception) {  }
        return;
    }
于 2017-03-13T19:08:40.870 回答
0
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

在此之后,您可以使用以下行来避免错误..(访问被拒绝等)

request.Proxy = null;
于 2012-11-15T16:35:38.443 回答
0

仅供参考,Microsoft 建议不要将 FtpWebRequest 用于新开发

我们不建议您将 FtpWebRequest 类用于新开发。有关 FtpWebRequest 的更多信息和替代方法,请参阅 WebRequest 不应在 GitHub 上使用。

GitHub 链接指向此 SO 页面,其中包含第三方 FTP 库的列表,例如FluentFTP

于 2021-02-01T19:15:50.417 回答