Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a cryptostream and would like to add a progress bar to this stream to let the user know how far through an encryption/decryption they are.

progress bar is called progressbar1

The cryptoStream code:

C#
using (FileStream inputFileStream = File.Open(inputFile, FileMode.Open))
               using (FileStream outputFileStream = File.Open(encryptedFile, FileMode.Create))
               {
                   using (DESCryptoServiceProvider tds = new DESCryptoServiceProvider())
                   {
                       tds.Key = keyBytes;
                       tds.IV = ivBytes;

                       ICryptoTransform cryptoTransform = tds.CreateEncryptor();

                       using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, cryptoTransform, CryptoStreamMode.Write))
                       {
                           byte[] buffer = new byte[inputFileStream.Length];
                           inputFileStream.Read(buffer, 0, buffer.Length);
                           cryptoStream.Write(buffer, 0, buffer.Length);
                           cryptoStream.Close();
Posted
Comments
Sergey Alexandrovich Kryukov 28-Jun-15 13:56pm    
What have you tried so far?
—SA

1 solution

You can use this progress bar: https://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar%28v=vs.110%29.aspx[^].

But you don't have progress to show, and probably you don't need to show it — you read and write all data at once.

For showing progress, you should break your stream in chunks. In your loop, you need to summarize the number of bytes read from input and use it as Value if the Maximum is the total size of the input stream. Or you can do similar calculations on output stream, but then you need to have correct evaluation of its full size before it's written.

If you do your calculations in a separate thread (recommended in most cases), you would need to notify the UI with progress bar update not directly, but in the UI thread, using Dispatcher.Invoke or Dispatcher.BeginInvoke. Please see my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900