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

情到浓时终转凉″ 提交于 2019-12-11 01:33:49

问题


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/



来源:https://stackoverflow.com/questions/7774648/how-can-convert-this-c-sharp-code-to-c-cli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!