如何将这个C#代码转换为C ++ / CLI

如何将这个C#代码转换为C ++ / CLI

问题描述:

如何将C#代码段转换为C ++ / CLI:

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

特别是这部分 byte [] retVal = md5。 ComputeHash(file);

*使用C ++ / CLI中提供的堆栈语义自动处理对象。对圣C ++ RAII模式的仿真,即使代码抛出异常,对象也会被释放。想象它作为编译器自动生成C#使用语句。看起来像这样:

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