How to convert an MD5 hash to a string and use it as a file name

16,004

Solution 1

How about this:

string filename = BitConverter.ToString(yourMD5ByteArray);

If you prefer a shorter filename without hyphens then you can just use:

string filename =
    BitConverter.ToString(yourMD5ByteArray).Replace("-", string.Empty);

Solution 2

System.Convert.ToBase64String

As a commenter pointed out -- normal base 64 encoding can contain a '/' character, which obivously will be a problem with filenames. However, there are other characters that are usable, such as an underscore - just replace all the '/' with an underscore.

string filename = Convert.ToBase64String(md5HashBytes).Replace("/","_");

Solution 3

Try this:

Guid guid = new Guid(md5HashBytes);
string hashString = guid.ToString("N"); 
// format: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

string hashString = guid.ToString("D"); 
// format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

string hashString = guid.ToString("B"); 
// format: {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

string hashString = guid.ToString("P"); 
// format: (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

Solution 4

This is probably the safest for file names. You always get a hex string and never worry about / or +, etc.

        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(inputString));
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        string hashed = sBuilder.ToString();

Solution 5

Try this:

string Hash = Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("sample")));
//input "sample" returns = Xo/5v1W6NQgZnSLphBKb5g==

or

string Hash = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("sample")));
//input "sample" returns = 5E-8F-F9-BF-55-BA-35-08-19-9D-22-E9-84-12-9B-E6
Share:
16,004
Nguyen Anh Duc
Author by

Nguyen Anh Duc

Software developer from just outside Sydney. Enjoy sport and music in my spare time.

Updated on June 09, 2022

Comments

  • Nguyen Anh Duc
    Nguyen Anh Duc about 2 years

    I am taking the MD5 hash of an image file and I want to use the hash as a filename.

    How do I convert the hash to a string that is valid filename?

    EDIT: toString() just gives "System.Byte[]"