My C# UploadFile method successfully uploads a file, but then my UI hangs...
Posted
by
kyrathaba
on Stack Overflow
See other posts from Stack Overflow
or by kyrathaba
Published on 2011-01-01T20:45:05Z
Indexed on
2011/01/01
20:54 UTC
Read the original article
Hit count: 209
I have a simple WinForms test application in C#. Using the following method, I'm able to upload a file when I invoke the method from my button's Click event handler. The only problem is: my Windows Form "freezes". I can't close it using the Close button. I have to end execution from within the IDE (Visual C# 2010 Express edition). Here are the two methods:
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 {
}
}
which gets called here:
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");
}
}
© Stack Overflow or respective owner