C# 从FTP上传文件和下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13109823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload file and download file from FTP
提问by Spreadzz
I am trying to make a program that uploads/downloads .exefile to a FTP
我正在尝试制作一个将.exe文件上传/下载到FTP
I tried using FtpWebRequest, but I only succeed to upload and download .txt files.
我尝试使用FtpWebRequest,但我只能成功上传和下载 .txt 文件。
Then i found here a solution for downloading using the WebClient:
然后我在这里找到了使用以下方法下载的解决方案WebClient:
WebClient request = new WebClient();
request.Credentials = new NetworkCredential("username", "password");
byte[] fileData = request.DownloadData("ftp://myFTP.net/");
FileStream file = File.Create(destinatie);
file.Write(fileData, 0, fileData.Length);
file.Close();
This solution works. But I seen that WebClienthas a method DownloadFilewhich did not worked. I think because it doesn't work on FTPonly on HTTP. Is my assumption true? If not how can I get it to work?
此解决方案有效。但我看到WebClient有一种方法DownloadFile不起作用。我认为因为它FTP不仅适用于HTTP. 我的假设是真的吗?如果不是,我怎样才能让它工作?
And is there any other solution for uploading/downloading a .exefile to ftp using FtpWebRequest?
还有其他解决方案可以.exe使用 ftp上传/下载文件FtpWebRequest吗?
回答by JohnLBevan
You need to say whether you're uploading text or binary files. Add the following line after request is declared & initialised:
您需要说明是上传文本文件还是二进制文件。在声明和初始化请求后添加以下行:
request.UseBinary = true;
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.usebinary.aspx
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.usebinary.aspx
回答by newbieguy
Uploading is easy...
上传很简单...
void Upload(){
Web client = new WebClient();
client.Credentials = new NetworkCredential(username, password);
client.BaseAddress = "ftp://ftpsample.net/";
client.UploadFile("sample.txt", "sample.txt"); //since the baseaddress
}
下载也很容易...我在下面制作的代码使用 BackgroundWorkerBackgroundWorker(因此它不会在下载开始时冻结界面/应用程序)。另外,我使用了缩短了代码lambda拉姆达
(=>)(=>)。void Download(){
Web client = new WebClient();
client.Credentials = new NetworkCredential(username, password);
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += (s, e) => {
client.DownloadFile("ftp://ftpsample.net/sample.zip", "sample.zip");
};
bg.RunWorkerCompleted += (s, e) => { //when download is completed
MessageBox.Show("done downloading");
download1.Enabled = true; //enable download button
progressBar.Value = 0; // reset progressBar
};
bg.RunWorkerAsync();
download1.Enabled = false; //disable download button
while (bg.IsBusy)
{
progressBar.Increment(1); //well just for extra/loading
Application.DoEvents(); //processes all windows messages currently in the message queue
}
}
You can also use DownloadFileAsyncmethod to show real progress file downloading:
您还可以使用DownloadFileAsync方法来显示文件下载的真实进度:
client.DownloadFileAsync(new Uri("ftp://ftpsample.net/sample.zip"), "sample.zip");
client.DownloadProgressChanged += (s, e) =>
{
progressBar.Value = e.ProgressPercentage; //show real download progress
};
client.DownloadFileCompleted += (s, e) =>
{
progressBar.Visible = false;
// other codes after the download
};
//You can remove the 'while' statement and use this ^
回答by Martin Prikryl
Both WebClient.UploadFileand WebClient.DownloadFilework correctly for FTP as well as binary files.
无论WebClient.UploadFile和WebClient.DownloadFile正确的FTP以及二进制文件的工作。
Upload
上传
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile(
"ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
If you need a greater control, that WebClientdoes not offer (like TLS/SSL encryption, ascii/text transfer mode, etc), use FtpWebRequest. Easy way is to just copy a FileStreamto FTP stream using Stream.CopyTo:
如果您需要更好的控制WebClient(如TLS/SSL 加密、ascii/文本传输模式等),请使用FtpWebRequest. 简单的方法是FileStream使用Stream.CopyTo以下命令将 a 复制到 FTP 流:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
If you need to monitor an upload progress, you have to copy the contents by chunks yourself:
如果您需要监控上传进度,您必须自己分块复制内容:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
byte[] buffer = new byte[10240];
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, read);
Console.WriteLine("Uploaded {0} bytes", fileStream.Position);
}
}
For GUI progress (WinForms ProgressBar), see:
How can we show progress bar for upload with FtpWebRequest
对于 GUI 进度 (WinForms ProgressBar),请参阅:
如何使用 FtpWebRequest 显示上传进度条
If you want to upload all files from a folder, see
Recursive upload to FTP server in C#.
如果要上传文件夹中的所有文件,请参阅
在 C# 中递归上传到 FTP 服务器。
Download
下载
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");
If you need a greater control, that WebClientdoes not offer (like TLS/SSL encryption, ascii/text transfer mode, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStreamusing Stream.CopyTo:
如果您需要更好的控制WebClient(如TLS/SSL 加密、ascii/文本传输模式等),请使用FtpWebRequest. 简单的方法是将 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);
}
If you need to monitor a download progress, you have to copy the contents by chunks yourself:
如果您需要监控下载进度,您必须自己分块复制内容:
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);
}
}
For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar
有关 GUI 进度 (WinForms ProgressBar),请参阅:
FtpWebRequest FTP download with ProgressBar
If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.
如果要从远程文件夹
下载所有文件,请参阅C# 通过 FTP 下载所有文件和子目录。

