Files
Umbraco-CMS/src/Umbraco.Core/HashCodeCombiner.cs

98 lines
2.7 KiB
C#
Raw Normal View History

using System;
using System.Globalization;
using System.IO;
namespace Umbraco.Core
{
2017-07-20 11:21:28 +02:00
/// <summary>
/// Used to create a hash code from multiple objects.
/// </summary>
/// <remarks>
/// .Net has a class the same as this: System.Web.Util.HashCodeCombiner and of course it works for all sorts of things
/// which we've not included here as we just need a quick easy class for this in order to create a unique
/// hash of directories/files to see if they have changed.
/// </remarks>
internal class HashCodeCombiner
{
private long _combinedHash = 5381L;
2017-07-20 11:21:28 +02:00
internal void AddInt(int i)
{
_combinedHash = ((_combinedHash << 5) + _combinedHash) ^ i;
}
2017-07-20 11:21:28 +02:00
internal void AddObject(object o)
{
AddInt(o.GetHashCode());
}
2017-07-20 11:21:28 +02:00
internal void AddDateTime(DateTime d)
{
AddInt(d.GetHashCode());
}
internal void AddString(string s)
{
if (s != null)
AddInt((StringComparer.InvariantCulture).GetHashCode(s));
}
2017-07-20 11:21:28 +02:00
internal void AddCaseInsensitiveString(string s)
{
if (s != null)
AddInt((StringComparer.InvariantCultureIgnoreCase).GetHashCode(s));
}
2017-07-20 11:21:28 +02:00
internal void AddFileSystemItem(FileSystemInfo f)
{
//if it doesn't exist, don't proceed.
if (!f.Exists)
return;
2017-07-20 11:21:28 +02:00
AddCaseInsensitiveString(f.FullName);
AddDateTime(f.CreationTimeUtc);
AddDateTime(f.LastWriteTimeUtc);
2017-05-30 10:50:09 +02:00
2017-07-20 11:21:28 +02:00
//check if it is a file or folder
var fileInfo = f as FileInfo;
if (fileInfo != null)
{
AddInt(fileInfo.Length.GetHashCode());
}
2017-05-30 10:50:09 +02:00
2017-07-20 11:21:28 +02:00
var dirInfo = f as DirectoryInfo;
if (dirInfo != null)
{
foreach (var d in dirInfo.GetFiles())
{
AddFile(d);
}
foreach (var s in dirInfo.GetDirectories())
{
AddFolder(s);
}
}
}
2017-07-20 11:21:28 +02:00
internal void AddFile(FileInfo f)
{
AddFileSystemItem(f);
}
2017-07-20 11:21:28 +02:00
internal void AddFolder(DirectoryInfo d)
{
AddFileSystemItem(d);
}
2017-07-20 11:21:28 +02:00
/// <summary>
/// Returns the hex code of the combined hash code
/// </summary>
/// <returns></returns>
internal string GetCombinedHashCode()
{
return _combinedHash.ToString("x", CultureInfo.InvariantCulture);
}
2017-07-20 11:21:28 +02:00
}
}