mfgames-cil/src/MfGames.IO/Extensions/CryptographyFileInfoExtensions.cs

46 lines
1.5 KiB
C#

using MfGames.Cryptography;
using MfGames.Cryptography.Extensions;
using MfGames.Cryptography.Hashes;
namespace MfGames.IO.Extensions;
/// <summary>
/// Extensions for generating
/// </summary>
public static class CryptographyFileInfoExtensions
{
/// <summary>
/// Hashes the given input and returns the results.
/// </summary>
/// <param name="file">The FileInfo object or null.</param>
/// <param name="hash">The type of hash requested.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static byte[]? ToHashBytes(this FileInfo? file, HashType hash = HashType.Sha512)
{
if (file == null)
{
return null;
}
using FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
return hash.CreateHash().ComputeHash(stream);
}
/// <summary>
/// Hashes the given input and returns the results as a string.
/// </summary>
/// <param name="file">The FileInfo object or null.</param>
/// <param name="hash">The type of hash requested.</param>
/// <param name="format">The format of the requested string.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static string? ToHashString(
this FileInfo? file,
HashType hash = HashType.Sha512,
ByteStringFormat format = ByteStringFormat.LowercaseHex
)
{
return file?.ToHashBytes(hash).ToByteString(format);
}
}