How can convert this C# code to C++/CLI

2019-07-16 21:41发布

问题:

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);

回答1:

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);
    }
};


回答2:

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/



标签: c# c++-cli