Reputation: 11
I have a document in memory of type XmlDocument and a file loaded from a directory that is an xml file. I would like to compare these the fastest way possible.
Currently this is how I am doing it...but this is a hash and is not as fast as byte for byte. I would like to revise this to be byte by byte..but would like to check for anything that may speed this up....such as a quick length comparison. I am not sure if I can check length since one is in memory and the other is loaded from a file. The file names are always the same..so I cannot check that.
protected bool AreFilesTheSame(XmlDocument doc, string fileToCompareTo)
{
if (!File.Exists(fileToCompareTo))
return (false);
try
{
SHA1CryptoServiceProvider cryptNewPub = new SHA1CryptoServiceProvider();
byte[] xmlBytes = Encoding.UTF8.GetBytes(doc.OuterXml.ToCharArray());
cryptNewPub.ComputeHash(xmlBytes);
SHA1CryptoServiceProvider cryptOldPub = new SHA1CryptoServiceProvider();
FileStream fileStream = File.OpenRead(fileToCompareTo);
cryptOldPub.ComputeHash(fileStream);
fileStream.Close();
if (cryptNewPub.Hash.Length != cryptOldPub.Hash.Length)
return (false);
for (int i = 0; i < cryptNewPub.Hash.Length; i++)
{
if (cryptNewPub.Hash[i] != cryptOldPub.Hash[i])
return (false);
}
return (true);
}
catch
{
return (false);
}
}
Upvotes: 1
Views: 68
Reputation: 6333
Perhaps the easiest way is to load the second XML file and compare the OuterXML:
protected bool AreFilesTheSame(XmlDocument doc, string fileToCompareTo)
{
if (!File.Exists(fileToCompareTo))
return (false);
try
{
XmlDocument doc2 = new XmlDocument();
doc2.Load(fileToCompareTo);
return doc.OuterXml == doc2.OuterXml;
}
catch
{
return (false);
}
}
Upvotes: 1