kyrathaba
kyrathaba

Reputation: 11

My C# UploadFile method successfully uploads a file, but then my UI hangs

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");
        }
    }

Upvotes: 1

Views: 1879

Answers (1)

JBSnorro
JBSnorro

Reputation: 6746

You forgot to ask a question. I assume it is you want to know how to avoid the freezing. The way you implemented the uploading, it takes up the entire thread for a relatively long time. This is not bad, but it is bad if that thread has other important tasks, in this case the UI.

If threading it new to you, you should really look into it, because the following solution is just a simple fix, it isn't great, but it works. Replace the call to UploadFile with

        new System.Threading.Thread(() => client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt")).Start();

Upvotes: 1

Related Questions