public static void SaveMD5Stream(AlternateDataStreamInfo md5StreamInfo, byte[] fileHash, DateTime fileWriteTimeUtc) { FileStream md5Stream = md5StreamInfo.OpenWrite(); MD5Descriptor descriptor = new MD5Descriptor(); descriptor.FileHash = fileHash; descriptor.FileWriteTimeUtc = fileWriteTimeUtc; descriptor.WriteToStream(md5Stream); md5Stream.Close(); }
public static MD5StreamStatus TestMD5Stream(FileInfo fileInfo) { byte[] fileHash = GetFileHash(fileInfo.FullName); AlternateDataStreamInfo md5StreamInfo = FileSystem.GetAlternateDataStream(fileInfo, MD5StreamName); if (md5StreamInfo.Exists) { Stream md5Stream = md5StreamInfo.OpenRead(); MD5Descriptor descriptor = MD5Descriptor.ReadFromStream(md5Stream); if (descriptor == null) { return(MD5StreamStatus.Invalid); } if (DateTime.Equals(fileInfo.LastWriteTimeUtc, descriptor.FileWriteTimeUtc)) { if (ByteUtils.AreByteArraysEqual(fileHash, descriptor.FileHash)) { return(MD5StreamStatus.Correct); } else { return(MD5StreamStatus.Incorrect); } } else // file was updated since MD5 was stored { SaveMD5Stream(md5StreamInfo, fileHash, fileInfo.LastWriteTimeUtc); // We revert to the last write time before the ADS was written File.SetLastWriteTimeUtc(fileInfo.FullName, fileInfo.LastWriteTimeUtc); return(MD5StreamStatus.Updated); } } else { SaveMD5Stream(md5StreamInfo, fileHash, fileInfo.LastWriteTimeUtc); // We revert to the last write time before the ADS was written File.SetLastWriteTimeUtc(fileInfo.FullName, fileInfo.LastWriteTimeUtc); return(MD5StreamStatus.Created); } }
/// <summary> /// Will return null if descriptor is invalid /// </summary> public static MD5Descriptor ReadFromStream(Stream stream) { Dictionary <string, string> properties; try { properties = ReadProperties(stream); } catch (ArgumentException) { return(null); } if (properties == null) { return(null); } if (properties.ContainsKey("MD5") && properties.ContainsKey("FileWriteTimeUtc")) { MD5Descriptor descriptor = new MD5Descriptor(); string md5String = properties["MD5"]; string fileWriteTimeUtcString = properties["FileWriteTimeUtc"]; try { descriptor.FileHash = HexStringToBytes(md5String); descriptor.FileWriteTimeUtc = DateTime.Parse(fileWriteTimeUtcString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); } catch { return(null); } return(descriptor); } return(null); }