private void CopyOrMove(String fileFullPath, String targetFile, String hash) { try { File.Copy(fileFullPath, targetFile, true); using (OrganizerDatabaseContext context = new OrganizerDatabaseContext()) { bool retain = true; if (!bool.TryParse(archive.retain, out retain)) retain = true; MediaFile mediaFile = new MediaFile(); mediaFile.ArchiveDateTime = DateTime.UtcNow; mediaFile.ContentHash = hash; mediaFile.CreatedDateTime = DateTime.UtcNow; mediaFile.MarkForDelete = retain; mediaFile.OriginalFileName = fileFullPath; mediaFile.TargetFileName = targetFile; context.MediaFiles.Add(mediaFile); context.SaveChanges(); } } catch { } }
private static void Archive(String file, DateTime createTime, Archive archive) { String ext = Path.GetExtension(file); String folder = createTime.GetFolderName(); String targetDir = Path.Combine(archive.DestinationFullPath, folder); String targetFile = Path.Combine(targetDir, $"{createTime.ToString("MM-dd-yyyy")}_{DateTime.UtcNow.Ticks.ToString()}{ext}"); MD5 hasher = MD5.Create(); // Copy the file if it doesnt already exist. try { // We might need to create the directory. CreateDirectory(targetDir); String hash = null; using (FileStream stream = File.OpenRead(file)) { hash = Convert.ToBase64String(hasher.ComputeHash(stream)); } // Does this file already exist in the databse? if(!MediaFile.Exists(hash)) { using (OrganizerDatabaseContext context = new OrganizerDatabaseContext()) { MediaFile mediaFile = new MediaFile(); mediaFile.ArchiveDateTime = mediaFile.CreatedDateTime = DateTime.UtcNow; mediaFile.ContentHash = hash; mediaFile.OriginalFileName = file; mediaFile.TargetFileName = targetFile; context.MediaFiles.Add(mediaFile); context.SaveChanges(); } } else { // Overwrite it if we can. MediaFile existingFile = MediaFile.GetByHash(hash); if(existingFile != null) // Should never be the case. { if(!File.Exists(existingFile.TargetFileName)) { targetFile = existingFile.TargetFileName; } else { Console.WriteLine($"Skipping: {file}."); } } } // Copy it over. try { Console.WriteLine($"Archiving: {file}."); File.Copy(file, targetFile); } catch { // Delete the media file if we couldnt copy it over. MediaFile.DeleteByHash(hash); } } catch (Exception e) { } }