Click here to Skip to main content
15,920,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi im trying to make my encryption program run without erroring when a wrong encryption key is used so i thought a try statement was needed but i dont know how to implement that into my program.
C#
private void Decrypt_Click(object sender, RoutedEventArgs e)
{    
    {
        Stream myStream;
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        //saveFileDialog1.Filter = "Save As";
        saveFileDialog1.RestoreDirectory = true;

        if (saveFileDialog1.ShowDialog() == true)
        {
            if ((myStream = saveFileDialog1.OpenFile()) != null)
                myStream.Close();
            {
                UnicodeEncoding ue = new UnicodeEncoding();
                byte[] key = ue.GetBytes(Genkey.Text);
                string cryptFile = saveFileDialog1.FileName;
                using (FileStream fileCrypt = new FileStream(cryptFile, FileMode.Create))
                {
                    using (AesManaged Decrypt = new AesManaged())
                    {
                        using (CryptoStream cs = new CryptoStream(fileCrypt, Decrypt.CreateDecryptor(key, key), CryptoStreamMode.Write))
                        {
                            using (FileStream fileInput = new FileStream(Openfile.Text, FileMode.Open))
                            {
                                Decrypt.KeySize = 256;
                                Decrypt.BlockSize = 128;
                                int data;
                                while ((data = fileInput.ReadByte()) != -1)
                                    cs.WriteByte((byte)data);
                            }
                        }
                    }
                }
                MessageBox.Show("File Successfully Decrypted", "Decrypted!");
            }
        }
    }
}
Posted
Updated 21-May-15 8:35am
v2

1 solution

In a try...catch block, all of your code which might generate (throw) an exception if something goes wrong comes in the try block. The code in the try section executes by default. However, if there is some error underground and the exception is to be thrown, the try block is no longer executed and the catch block is executed further where you handle the error or show an error message.

If your code is supposed to run from line 1 to line x and there are some chances of getting a error. You can wrap the code (from line 1 to line x) inside the try section. And add a catch block after it, to catch the exception that thrown.

You code would look like this,

C#
private void Decrypt_Click(object sender, RoutedEventArgs e)
{    
    try { // Start a try catch block
        Stream myStream;
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        //saveFileDialog1.Filter = "Save As";
        saveFileDialog1.RestoreDirectory = true;
 
        if (saveFileDialog1.ShowDialog() == true)
        {
            if ((myStream = saveFileDialog1.OpenFile()) != null)
                myStream.Close();
            {
                UnicodeEncoding ue = new UnicodeEncoding();
                byte[] key = ue.GetBytes(Genkey.Text);
                string cryptFile = saveFileDialog1.FileName;
                using (FileStream fileCrypt = new FileStream(cryptFile, FileMode.Create))
                {
                    using (AesManaged Decrypt = new AesManaged())
                    {
                        using (CryptoStream cs = new CryptoStream(fileCrypt, Decrypt.CreateDecryptor(key, key), CryptoStreamMode.Write))
                        {
                            using (FileStream fileInput = new FileStream(Openfile.Text, FileMode.Open))
                            {
                                Decrypt.KeySize = 256;
                                Decrypt.BlockSize = 128;
                                int data;
                                while ((data = fileInput.ReadByte()) != -1)
                                    cs.WriteByte((byte)data);
                            }
                        }
                    }
                }
                MessageBox.Show("File Successfully Decrypted", "Decrypted!");
            }
        }
    }
    catch (Exception er) { // Catch the (base) exception and show an error message
        MessageBox.Show("Sorry, there was error. Error message: " + er.Message);
    }
}


Try catch is widely used in all programming language to let you handle any unwanted case where your program might break. Read more about it on MSDN: https://msdn.microsoft.com/en-us/library/0yd65esw.aspx[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 21-May-15 17:05pm    
You explain it all well enough, except main thing: there is no a need to handle exception like that in this method at all.
The exception does not do anything specific to this method, so the right approach will be "let go". In UI, such exceptions should be handled at the level of main event loop; application types have special events for that. Exceptions should be handled in each thread, but rarely, only in few special strategically chosen points I call "competency points".
—SA
Afzaal Ahmad Zeeshan 21-May-15 18:48pm    
Or perhaps the key should be checked against in a simple if else block or something like that. That would be better for him.
Sergey Alexandrovich Kryukov 21-May-15 18:53pm    
Maybe. In all cases, the exception should not be handled in general way too locally.
—SA
Afzaal Ahmad Zeeshan 21-May-15 18:57pm    
Or in other sense, allowing the framework to handle each and every exception and show an error message is also not a good method to write software. Programmer should himself write the logic in a way to minimize the chances of exceptions, and then he should handle the exceptions where he is not left with any other chance, like the network-based exceptions such as when there is no internet connection etc; WebException.
Sergey Alexandrovich Kryukov 21-May-15 19:32pm    
No, wait a second. Minimizing chances of exception has nothing to do with minimization of exception handling. Exception handling should be minimized, but exceptions themselves, in most cases, should be let go. Do you think this is unusual approach? Moreover, so called "defensive programming" is mostly evil. Programming should be more offensive. You can check if the file exists or you can just open it, no matter what. What's better? In most cases, it's better not to check anything. On top of UI, normal exception mechanism will tell you that file is not found, so why checking it. Only if there are many different kinds of file for different and confusingly complex purposes, check up makes sense, but only if you can add extra information about the problem. But even then you should not handle exception locally. You should re-throw exception of different type, more customized type, application-specific.
—SA

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