Instantiating a list of parameterized types, making beter use of Generics and Linq
Posted
by DanO
on Stack Overflow
See other posts from Stack Overflow
or by DanO
Published on 2010-03-09T00:35:31Z
Indexed on
2010/03/09
0:36 UTC
Read the original article
Hit count: 690
I'm hashing a file with one or more hash algorithms. When I tried to parametrize which hash types I want, it got a lot messier than I was hoping.
I think I'm missing a chance to make better use of generics or LINQ. I also don't like that I have to use a Type[] as the parameter instead of limiting it to a more specific set of type (HashAlgorithm descendants), I'd like to specify types as the parameter and let this method do the constructing, but maybe this would look better if I had the caller new-up instances of HashAlgorithm to pass in?
public List<string> ComputeMultipleHashesOnFile(string filename, Type[] hashClassTypes)
{
var hashClassInstances = new List<HashAlgorithm>();
var cryptoStreams = new List<CryptoStream>();
FileStream fs = File.OpenRead(filename);
Stream cryptoStream = fs;
foreach (var hashClassType in hashClassTypes)
{
object obj = Activator.CreateInstance(hashClassType);
var cs = new CryptoStream(cryptoStream, (HashAlgorithm)obj, CryptoStreamMode.Read);
hashClassInstances.Add((HashAlgorithm)obj);
cryptoStreams.Add(cs);
cryptoStream = cs;
}
CryptoStream cs1 = cryptoStreams.Last();
byte[] scratch = new byte[1 << 16];
int bytesRead;
do { bytesRead = cs1.Read(scratch, 0, scratch.Length); }
while (bytesRead > 0);
foreach (var stream in cryptoStreams)
{
stream.Close();
}
foreach (var hashClassInstance in hashClassInstances)
{
Console.WriteLine("{0} hash = {1}", hashClassInstance.ToString(), HexStr(hashClassInstance.Hash).ToLower());
}
}
© Stack Overflow or respective owner