private bool CalculateFileHash(QueueItem item, BackgroundWorker bw) { if (item == null) throw new ArgumentNullException("item"); if (item.File.Exists) { string FileHash = String.Empty; if (item.Type == HashType.CRC) { uint crc; try { crc = Crc32.GetFileCRC32(item.File.FullName, ref _BytesProcessed, bw); } catch (Exception ex) { item.SetResultStatus(QueueItemResult.FileAccessViolation); return false; } FileHash = StringUtilities.UInt32ToHex(crc); } else if (item.Type == HashType.MD5) { byte[] md5; try { md5 = Md5.GetFileMD5(item.File.FullName, ref _BytesProcessed, bw); } catch (Exception ex) { item.SetResultStatus(QueueItemResult.FileAccessViolation); return false; } FileHash = StringUtilities.ByteArrayToHex(md5); } item.SetFileHash(FileHash); return true; } else { item.SetResultStatus(QueueItemResult.FileNotFound); } return false; }
private bool AppendHashToFileName(QueueItem item) { if (item.File.Exists) { // Determine which QueueItem hash value is avaliable string FileHash; if (!String.IsNullOrEmpty(item.FileHash)) { FileHash = item.FileHash; } else if (!String.IsNullOrEmpty(item.TestHash)) { FileHash = item.TestHash; } else { // This would be pretty pointless if we didnt have a hash to append item.SetResultStatus(QueueItemResult.HashAppendFailed); return false; } // Generate the new file name string NewFileName; if (item.File.Name.IndexOf('.') > -1) { NewFileName = item.File.Name.Substring(0, item.File.Name.LastIndexOf('.')) + " [" + FileHash + "]" + item.File.Extension; } else { NewFileName = item.File.Name + "[" + FileHash + "]"; } // Rename the file, catching common exceptions try { item.File.MoveTo(Path.Combine(item.File.DirectoryName, NewFileName)); } catch (FileLoadException) { item.SetResultStatus(QueueItemResult.FileAccessViolation); return false; } catch (Exception ex) { item.SetResultStatus(QueueItemResult.HashAppendFailed); return false; } } else { // File didnt exist item.SetResultStatus(QueueItemResult.FileNotFound); return false; } // Success item.SetResultStatus(QueueItemResult.HashAppended); return true; }