我如何从FTP获取文件(使用c#)

本文关键字:使用 文件 获取 FTP | 更新日期: 2023-09-27 18:18:45

现在我知道如何将文件从一个目录复制到另一个目录,这真的很简单。

但是现在我需要对来自FTP服务器的文件做同样的操作。你能给我一些例子如何从FTP获取文件,而改变它的名字?

我如何从FTP获取文件(使用c#)

看一下如何使用FTP下载文件或下载目录FTP和c#下的所有文件

 // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            Console.WriteLine(reader.ReadToEnd());
            Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
            reader.Close();
            reader.Dispose();
            response.Close();  

编辑如果你想重命名FTP服务器上的文件看看这个Stackoverflow问题

最简单的方法

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

它接受指向源远程文件的URL和指向目标本地文件的路径。因此,如果需要,您可以为本地文件使用不同的名称。

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

高级选项

如果你需要更大的控制,WebClient不提供(如TLS/SSL加密,ASCII模式,活动模式等),使用FtpWebRequest。简单的方法是使用Stream.CopyTo将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"))
{
    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下载所有文件和子目录