我需要通过 FTP 将文件上传到我的服务器,但现在已经不是 1995 年了,所以我想我可能想让它异步或在后台上传文件,以免使 UI 变得无响应。
来自 this 的代码页面有一个通过 FTP 同步上传文件的完整示例。我怎样才能把它变成一个异步方法?
同步代码:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
}
}
我应该把它扔进 BackgroundWorker 吗?
注意事项:
我不需要知道传输/上传的进度。我只需要知道状态(正在上传或已完成)。
我是一名优秀的程序员,十分优秀!