【发布时间】:2011-06-02 07:40:52
【问题描述】:
我有一个简单的 C# WinForms 测试应用程序。使用以下方法,当我从按钮的 Click 事件处理程序调用该方法时,我可以上传文件。唯一的问题是:我的 Windows 窗体“冻结”。我无法使用关闭按钮关闭它。我必须从 IDE(Visual C# 2010 Express 版)中结束执行。以下是两种方法:
public void UploadFile(string FullPathFilename) {
string filename = Path.GetFileName(FullPathFilename);
try {
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
StreamReader sourceStream = new StreamReader(FullPathFilename);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
requestStream.Close();
sourceStream.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Upload error");
}
finally {
}
}
在这里调用:
private void btnUploadTxtFile_Click(object sender, EventArgs e) {
string username = "my_username";
string password = "my_password";
string host = "ftp://mywebsite.com";
try {
clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password);
client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Upload problem");
}
}
【问题讨论】: