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.
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.
I have tried to code two functions for generating and comparing the hash but I am unsure how to link all of them.
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.