Search code examples
c#file-iofilestreampercentage

C# Calculating Percentage of AES Encryption/Decryption


I'm trying to encrypt/decrypt a file using AES 256 bit with the code I got from here. The full code I am using is seen here. I was wondering how I could calculated the percentage done of both encryption/decryption in the while loop as it writes to the file. For example in encryption:

while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
    cs.Write(buffer, 0, read);
    //int percentage = Calculate percentage done here?
}

And in decryption:

while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
    fsOut.Write(buffer, 0, read);
    //int percentage = Calculate percentage done here?
}

Solution

  • I was able to get it worked with both encryption and decryption. For encryption, I used:

    var percentComplete = (float)fsIn.Position * 100 / fsIn.Length;
    

    As John Wu stated. For decryption, I used:

    var percentComplete = (float)fsOut.Position * 100 / fsCrypt.Length;
    

    This works because it divides the Position(x100) by the total length of the encrypted file, as opposed to fsOut.Length; which only returns the data that's been written out to the new decrypted file.