C# FtpWebRequest下载文件

C# FtpWebRequest下载文件,c#,.net,ftp,ftpwebrequest,ftpwebresponse,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 = WebReque

以下代码旨在通过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(即我有权限)。有人能告诉我为什么会出现这个错误吗?

您可能会感兴趣:

URI可以是相对的,也可以是绝对的。 如果URI的格式为 (%2f是 一个转义的“/”),则URI为 绝对,当前目录为 /路径。但是,如果URI是 表格“”,第一 .NET Framework登录到FTP 服务器(使用用户名和 由凭据设置的密码 属性),然后是当前目录 设置为/path


我知道这是一个老帖子,但我在这里添加供将来参考。我发现了一个解决方案:

    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的优秀建议进行更新

我也有同样的问题

我的解决方案是将
public\uhtml
文件夹插入下载URL

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

myhost.com/public_html/myimages/image.png

网址:

www.myhost.com/myimages/image.png

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


我希望它能帮助你。

最简单的方法
   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;
    }
使用.NET framework从FTP服务器下载二进制文件最简单的方法是:


高级选项 仅当您需要更大的控制时才使用
WebClient
不提供的控制(如进度监控、ascii/文本传输模式等)。简单的方法是使用以下命令将FTP响应流复制到
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类。有关FtpWebRequest的更多信息和替代方案,请参阅不应在GitHub上使用WebRequest


GitHub链接指向包含第三方FTP库列表的目录,例如。

我发现wireshark对此类内容很有用。您可以设置筛选器以查看您的计算机和服务器之间的FTP通信。如果将UseAssive设置为false,会发生什么情况?我从未让任何服务器使用被动模式工作。根据我的经验,这通常会导致超时错误,因为它试图使用防火墙阻止的端口。据我所知,其余代码对我来说似乎没问题。请注意,您应该处理IDisposable对象。最简单的方法是使用关键字
using
。你是对的,我刚接触C时就发布了这个回复。如果你要使用
WebClient
,而不是
FtpWebRequest
,你可以使用它的方法,而不是使用
文件流,这可能会更容易一些。有些事情WebClient不能做,但是(比如使用
ACTV
而不是
PASV
FTP:
FtpWebRequest.useAssemposive=false;
)默认情况下代理什么都不是。对我来说,这是处理非ASCII字符的问题,就像URL中的#,它们必须是url编码的。您是如何计算出缓冲区大小的数字“10240”的?@Donald.Record文件副本缓冲区大小通常为几KBs。它应该大于磁盘扇区大小。我不认为大于10KB有任何帮助。虽然实际使用的缓冲区为80KB。
    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;

    }
   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;
    }
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 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);
    }
}