using System; using System.IO; using System.Text; using System.Security.Cryptography; using System.Xml; namespace Differ { public class File { public File() { this.Path = ""; this.Name = ""; this.Hash = ""; this.Parent = null; } public File(string path, Folder parent = null) { this.Name = (new FileInfo(path).Name); this.Path = path; this.Parent = parent; this.Hash = GetHash(); } public string Name { get; private set; } public string Path { get; private set; } public Folder Parent { get; internal set; } public string Hash { get; private set; } protected bool Diffed = false; public string GetHash() { MD5CryptoServiceProvider provider = null; ASCIIEncoding encoder = null; FileStream fileStream = null; try { provider = new MD5CryptoServiceProvider(); encoder = new ASCIIEncoding(); fileStream = new FileStream(this.Path, FileMode.Open, FileAccess.Read); provider.Initialize(); byte[] hash = provider.ComputeHash(fileStream); StringBuilder hashBuilder = new StringBuilder(); foreach (var b in hash) { hashBuilder.Append(b.ToString("x2")); } return hashBuilder.ToString(); } catch (Exception) { return ""; } finally { // Dispose objects. if(fileStream != null) fileStream.Dispose(); if(provider != null) provider.Dispose(); } } public XmlNode GetNode(XmlDocument document) { XmlNode toReturn = document.CreateNode(XmlNodeType.Element, "File", ""); XmlAttribute hashAttribute = document.CreateAttribute("Hash"); hashAttribute.InnerText = Hash; XmlAttribute nameAttribute = document.CreateAttribute("Name"); nameAttribute.InnerText = this.Name; toReturn.Attributes.Append(nameAttribute); toReturn.Attributes.Append(hashAttribute); return toReturn; } public bool Matches(File file) { return (file.Name == this.Name) && (file.Hash == this.Hash); } public string GetRelativePath() { StringBuilder builder = new StringBuilder(); builder.Append(this.Parent.GetRelativePath()) .AppendFormat("\\{0}", this.Name); return builder.ToString(); } public void ParseFromXmlNode(XmlNode node) { foreach (XmlAttribute attribute in node.Attributes) { switch (attribute.Name) { case "Name": this.Name = attribute.InnerText; break; case "Hash": this.Hash = attribute.InnerText; break; default: break; } } } } }