我在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");
}
}
答案 0 :(得分:1)
你忘了问一个问题。我想你是想知道如何避免冻结。 实现上传的方式,它占用整个线程相对较长的时间。这不错,但如果该线程有其他重要任务,在这种情况下是UI,那就不好了。
如果它是新的线程,你应该仔细研究它,因为以下解决方案只是一个简单的解决方案,它不是很好,但它的工作原理。用<< / p>替换对UploadFile的调用
new System.Threading.Thread(() => client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt")).Start();