tags:

views:

2101

answers:

4

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[]"

+7  A: 

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("/","_");
Jonathan
I am gettig an error using that and if try with say test.jpg it works??
Malcolm
Looking at it there is "/" in the string and error is cannot find part pf path??
Malcolm
Either remove all "/" characters or use the approach I suggest in my answer.
sharptooth
You will need to convert all the / and + characters to, say, _ and - characters instead.
Chris Jester-Young
"+" characters are not prohibited, no need to remove them.
sharptooth
Converting to base 64 could have been a good idea, if it where not for the strange characters such as + - / that happens a lot when you use this encoding and that filesystems and parsers don't like
Johan Buret
+10  A: 

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);
LukeH
Ok, didn't know about this class, and it does the trick
Johan Buret
Note this uses hexadecimal encoding.
meandmycode
A: 

Technically using Base64 is bad if this is Windows, filenames are case insensitive (at least in explorers view).. but in base64, 'a' is different to 'A', this means that perhaps unlikely but you end up with even higher rate of collision..

A better alternative is hexadecimal like the bitconverter class, or if you can- use base32 encoding (which after removing the padding from both base64 and base32, and in the case of 128bit, will give you similar length filenames).

meandmycode
+2  A: 

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