1

I am newbie in C# and recently I tried to make a MD5 hash calculator. But everytime i check some file, the data remains in RAM until i close the program. In 50kb files or so it doesnt matter, but bigger files may not work. Any clues how can it be disposed or cleared after showing the result ? Thanks

private void button1_Click(object sender, EventArgs e)
    {
        MD5 md5hash = MD5.Create();
        string inputMD5;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string fileloc = openFileDialog1.FileName;
            byte[] block = File.ReadAllBytes(fileloc);
            byte[] data = md5hash.ComputeHash(block);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            inputMD5 = sBuilder.ToString();
            MessageBox.Show(inputMD5);
        }
stuartd
  • 70,509
  • 14
  • 132
  • 163
  • You may want to look at reading the file as a stream rather than all in one go for large files anyway. Then you can use the [`HashAlgorithm.ComputeHash(Stream)`](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm.computehash?view=netframework-4.7.2#System_Security_Cryptography_HashAlgorithm_ComputeHash_System_IO_Stream_) function. – Callum Watkins Feb 25 '19 at 15:36
  • 1
    Please read [this](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose) topic on MSDN. – Rex Feb 25 '19 at 15:36
  • This is not a duplicate for how to call garbage collection manually – Emond Feb 25 '19 at 15:38
  • `the data remains in RAM until i close the program` - How did you checked that? – Mat J Feb 25 '19 at 15:40
  • See the marked duplicates, that should address what it is you are trying to accomplish. It also reinforces why it is always important to include your end goal in your question so thank you for doing that. – Igor Feb 25 '19 at 15:42
  • `MD5` is an `IDisposable`-implementing class, so its creation and usage should be wrapped in a `using` construct. – Jesse C. Slicer Feb 25 '19 at 15:56

0 Answers0