Compare MD5 hash value of new file with existing hash value of files ASP.Net

  • Thread starter Thread starter Jason Phang
  • Start date Start date
J

Jason Phang

Guest
The program that I am writing now is able to generate the hash of the files and display it in a list when I run it. I would want to generate the hash value of the file when I upload and check it with the other hash value of the files before uploading. This is the code for my 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));
HashGenerator(path);
compareHash(path);
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 FileStream(path, FileMode.Open))
{
request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
request.Fields = "id";
request.Upload();
}
}
}

These below are the codes for generating the hash of the file upon upload and comparing the hash of the files.

public static string HashGenerator(string path)
{

using (var md5 = MD5.Create())
{
using (var stream = new FileStream(path, FileMode.Open))
{
return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", null).ToLower();
}
}
}

public static void compareHash(string path)
{

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.Equals(path))
{
throw new Exception("File already exists");
}

}

}

When i run the code, if it was a duplicated file, then the exception ("file already exists") will be thrown. Otherwise, if it is a new file, this error will be thrown. I am unsure how to be able to upload the file should the hash be a new hash.


System.IO.FileNotFoundException: Could not find file 'C:\Users\jpvon\source\repos\GoogleDriveRestApi_v3\GoogleDriveRestApi_v3\GoogleDriveFiles\IC.pdf'.







Jason

Continue reading...
 
Back
Top