0

I ve got the following code which

foreach (string dir in dirs) { //dirs all files in directory
    try{
       // Get an instance of WebClient
       WebClient client = new System.Net.WebClient();
       // parse the ftp host and file into a uri path for the upload
       Uri uri = new Uri(m_FtpHost + new FileInfo(dir).Name);
       // set the username and password for the FTP server
       client.Credentials = new System.Net.NetworkCredential(m_FtpUsername, m_FtpPassword);
       // upload the file asynchronously, non-blocking.
       client.UploadFileAsync(uri, "STOR",dir);
       }
       catch(Exception e){

            print(e.Message);
       }
}

Can I retrieve back the progress of the upload? I have in the dirs 4-5 files. I want exact the progress (not the files uploaded/(total files))

EDIT: Thus the right approach is the following:

public int percentage;

try{
    // Get an instance of WebClient
    WebClient client = new System.Net.WebClient();
    // parse the ftp host and file into a uri path for the upload 
    Uri uri = new Uri(m_FtpHost + new FileInfo(dir).Name);
    // set the username and password for the FTP server                      
    client.Credentials = new System.Net.NetworkCredential(m_FtpUsername, m_FtpPassword);
    // upload the file asynchronously, non-blocking.
    client.UploadProgressChanged += WebClientUploadProgressChanged; 
    client.UploadFileCompleted += WebClientUploadCompleted;
    client.UploadFileAsync(uri, "STOR",dir);

}

void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
    percentage =  e.ProgressPercentage;
}
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
    print( "Upload is finished. ");
}

I add this implementation to my code, however it seems that it doenst print anything in the console.

Jose Ramon
  • 5,572
  • 25
  • 76
  • 152
  • 1
    Look at this post on how to do it: http://stackoverflow.com/questions/982299/getting-the-upload-progress-during-file-upload-using-webclient-uploadfile – Sybren Dec 22 '15 at 08:08
  • @Sybren are you sure about that solution? How I will give the credentials of the server with that approach? – Jose Ramon Dec 22 '15 at 08:10
  • @JoseRamon "How I will give the credentials of the server?" AS IS, the same way you're doing it right now... – IronGeek Dec 22 '15 at 08:30
  • You can give the credentials in the same way. – Sybren Dec 22 '15 at 08:34

1 Answers1

1

WebClient contains a dedicated event for this

 public event UploadProgressChangedEventHandler UploadProgressChanged 

https://msdn.microsoft.com/en-us/library/system.net.webclient.uploadprogresschanged(v=vs.110).aspx

EDIT : HttpWebRequest approach based on a google result :

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "text/plain";

        request.Timeout = -1; //Infinite wait for the response.

        // Get the file information object.
        FileInfo fileInfo = new FileInfo("C:\\Test\\uploadFile.dat");

        // Set the file content length.
        request.ContentLength = fileInfo.Length;
        // Get the number of segments the file will be uploaded to the stream.
        int segments = Convert.ToInt32(fileInfo.Length / (1024 * 4));

        // Get the source file stream.
        using (FileStream fileStream = fileInfo.OpenRead())
        {
            // Create 4KB buffer which is file page size.
            byte[] tempBuffer = new byte[1024 * 4];
            int bytesRead = 0;

            // Write the source data to the network stream.
            using (Stream requestStream = request.GetRequestStream())
            {
                // Loop till the file content is read completely.
                while ((bytesRead = fileStream.Read(tempBuffer, 0, tempBuffer.Length)) > 0)
                {
                    // Write the 4 KB data in the buffer to the network stream.
                    requestStream.Write(tempBuffer, 0, bytesRead);

                    // Update your progress bar here using segment count.
                }
            }
        }
        // Post the request and Get the response from the server.
        using (WebResponse response = request.GetResponse())
        {
            // Request is successfully posted to the server.
        }
Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
  • I followed the example both for progress and completetion. In case of WebClientUploadCompleted I am getting the message when the upload is completed, however in the case of progressChanged it didnt printed anything in the console. What I am missing here? – Jose Ramon Dec 22 '15 at 10:11
  • You can try something like that `print(e.BytesSent * 100 / e.TotalBytesToSend);` – Quentin Roger Dec 22 '15 at 10:31
  • I tried to add print("####") inside the WebClientUploadProgressChanged and it seems that the code never goes inside that function. – Jose Ramon Dec 22 '15 at 10:44
  • You should first add eventHandlers and then call the method which will fire them. Do this `client.UploadProgressChanged += WebClientUploadProgressChanged;` before `client.UploadFileAsync(uri, "STOR",dir);` – Quentin Roger Dec 22 '15 at 11:12
  • I tried it I am receiving constantly zero progress. – Jose Ramon Dec 23 '15 at 10:17
  • Are you sure files are correctly uploaded on your server ? Now the `UploadProgressChanged` is fired ? if yes, `e.BytesSent` is always at 0 ? – Quentin Roger Dec 23 '15 at 10:19
  • The files are uploaded normally, I am receiving message from client.UploadFileCompleted += WebClientUploadComplete that the upload is complete, however percentage is alwarys zero. – Jose Ramon Dec 23 '15 at 10:30
  • It seems that it never goes inside WebClientUploadProgressChanged – Jose Ramon Dec 23 '15 at 10:39
  • Try to change your approach, switch on `HttpWebRequest` you will isolate your problem, check my edit. – Quentin Roger Dec 23 '15 at 10:54