Hi,
I am going to write a program which can calculate MD5 of a file even the file is in use.\
please help me to modify the code i am unable to change it after the number of tries.Thanks in advance........

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Drawing;
using System.Windows.Forms;

namespace RTMssp
{
    class checksum
    {

        public string calculator(string t)
        {
            try
            {

                FileStream f = new FileStream(t,
            FileMode.Open, FileAccess.Read, FileShare.Read, 8192);
                //SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                //sha1.ComputeHash(f);
                md5.ComputeHash(f);
                //byte[] hash = sha1.Hash;
                byte[] md5hash = md5.Hash;
                StringBuilder md5buff = new StringBuilder();
                //StringBuilder buff = new StringBuilder();
                foreach (byte hashByte in /*hash*/md5hash)
                {
                    //  buff.Append(String.Format("{0:X1}", hashByte));
                    md5buff.Append(String.Format("{0:X1}", hashByte));

                }
                f.Close();
                return md5buff.ToString();
                //code.Text = buff.ToString();

            }
            catch //here i want to add a code that if the file is in use it can calculate md5 
            {

                MessageBox.Show("Sorry The File May In Use.");
                return "no";
            }

        }

    }
}

I am going to write a program which can calculate MD5 of a file even the file is in use

if a file "is in use" means that someone has an exclusive lock to the file i.e. no one else can access the file until the lock's owner releases the lock. This is usually the case when someone writes to the file.

If someone writes to a file, file's content is changing and in that point it doesn't make sense to calculate MD5. I suggest building a list of those files you can't access. Once you've gone through all the files (I'm assuming you're calculating MD5s for a larger set of files), retry those files in the "unaccessible" files list (you may also wait for a while before retrying). Some files may now be accessible, some not.

Another reason why can't access some file, is inadequate or missing rights for the file. These files are usually system files (in System32 folder), paging file (pagefile.sys) etc. You won't get access to some of these files even with admin rights.

HTH

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.