How can I convert this segment of C# code to C++/CLI:
protected string GetMD5HashFromFile(string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
ASCIIEncoding enc = new ASCIIEncoding();
return enc.GetString(retVal);
}
Specially this part byte[] retVal = md5.ComputeHash(file);
Making liberal use of the stack semantics available in C++/CLI to automatically dispose objects. An emulation of the Holy C++ RAII pattern, the object gets disposed even when the code throws an exception. Think of it as the compiler automatically generating the C# using statement. Look like this:
using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;
using namespace System::Text;
ref class Example {
protected:
String^ GetMD5HashFromFile(String^ fileName)
{
FileStream file(fileName, FileMode::Open);
MD5CryptoServiceProvider md5;
array<Byte>^ retVal = md5.ComputeHash(%file);
return Convert::ToBase64String(retVal);
}
};
There's an example of using the crypto service provider from C++ to generate an MD5 in the top answer to this question:
http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/c0f97655-d953-4e3f-82b9-b70edaf1625b/