Question generate hash value for new file with Google Drive REST Api?

Jason Phang

Well-known member
Joined
Aug 13, 2019
Messages
46
Programming Experience
Beginner
I am able to upload files into the Google Drive. However, now I would want to generate a hash value for the new file that would be uploaded to the Google Drive so that it can be compared with the other hashes of the files and sort of like display a message if there is a duplicated hash. But for now, I am unsure on how should I generate the hash value of the new file.

File Upload to Google Drive:
  public static void FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                DriveService service = GetService();

                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
                Path.GetFileName(file.FileName));
                file.SaveAs(path);

                var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                FileMetaData.Name = Path.GetFileName(file.FileName);
                FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);

                 FilesResource.CreateMediaUpload request;

                  using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }

            }

        }

This allows me to upload the file to the Google Drive. I am wondering is there any built in functions that can generate the hash value of the file like for the file name and file mime in this code block.

Generate and Compare Hash:
        public static string HashGenerator(string path)
        {
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                using (var stream = System.IO.File.OpenRead(path))
                {
                    return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", null).ToLower();
                }

            }
        }

        public static bool CompareHash (string HashToCompare)
        {
            DriveService service = GetService();
            FilesResource.ListRequest FileListRequest = service.Files.List();
            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
            List<GoogleDriveFiles> FileList = new List<GoogleDriveFiles>();
            foreach (var file in files)
            {
                if (file.Md5Checksum == HashToCompare) return true;
              
            }

            return false;
        }

I have tried to code two functions for generating and comparing the hash but I am unsure how to link all of them.
 
Seems simple enough. Between lines 10 and 11 of your FileUpload(), call your HashGenerator() passing in the path to the file you intend to upload. That will return a hash in a string. Pass that string to your CompareHash(). If CompareHash() returns false, then proceed on with line 11 of FileUpload(). If it returns true, then you'll need to bail out of FileUpload() along with presenting the user with a message letting them know that a duplicate file already exists in their Google Drive.
 
At the moment, I have tried this and I tried checking around for how to display textbox in asp.net but they gave mostly for win forms.
File Upload, Generate Hash, Compare Hash:
        //file Upload to the Google Drive.
        public static void FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                DriveService service = GetService();

                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
                Path.GetFileName(file.FileName));
                file.SaveAs(path);

                HashGenerator(path);
                compareHash(path);

                var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                FileMetaData.Name = Path.GetFileName(file.FileName);
                FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);

                  FilesResource.CreateMediaUpload request;

                  using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }

            }

        }

        public static string HashGenerator(string path)
        {

            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                using (var stream = System.IO.File.OpenRead(path))
                {
                   return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", null).ToLower();
                }
            }
        }

        public static bool compareHash(string hashToCompare)
        {
            DriveService service = GetService();
            FilesResource.ListRequest FileListRequest = service.Files.List();
            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
            List<GoogleDriveFiles> FileList = new List<GoogleDriveFiles>();

            foreach (var file in files)
            {
                if (file.Md5Checksum == hashToCompare) return true;
                //Insert messagebox here?
            }

            return false;

        }

What would be the best way to display a message box?
 
If you are using asp.net, I wouldn't use a message box, I would use CSS and JS to display an elegant message to the user stylishly.

Since you ask assuming asp : <script>alert('My file message');</script> in your asp file or codebehind you can probably use
C#:
Response.Write("<script>alert('My file message');</script>");

You can also use this api call in windows apps :
C#:
        [DllImport("User32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(IntPtr intPtr, string uMsg, string sTle, int iType);
Call it with :
C#:
MessageBox((IntPtr)0, "Some file issue", "File title", 0);

On line 12, return the string HashGenerator, and then on line 13. perform a check to see if the value returned is a match to the file on the server. Your functions should be short and blunt, and I would separate the comparing function with a new function for acquiring info from the g.drive server. But that's just me, and how I like to keep it all simple. The purpose of functions is to do one thing, and not multiple things. Follow the k.i.s.s. principle.
 
Back
Top Bottom