views:

74

answers:

1

I'd like to ensure that a given file name is valid, even if it means replacing or removing some characters. I'm currently doing this:

Path.GetInvalidFileNameChars ().ToList ().ForEach (x => path.Replace (x, '-'));

But as far as I can tell, this is not guaranteed to yield a valid filename. Is there any better way than performing above pre-check followed by actually try-catching to open the file?

Edit: spot the bug in above code ;)

Minor addition: I'd prefer to keep the filename as readable as possible, so using some kind of BASE64 should be avoided.

+3  A: 

One of the way that we had used in past is to replace all characters that are not in some specific band (alpha-numeric and hyphen/underscores) with some special character such as hyphen. This is assuming that most File System allows this band. But its not safe on say some future FS that may not be allowing say numbers.

VinayC
Hardcore, but good idea - this appears to be a very safe way.
mafutrct
Yes - its safe way. We went this way because we were trying preserve the uploaded file name by storing in temp directory and we encountered issue when file was uploaded from mac machine. Of course, now we use generated file names to store in file store and actual name gets stored in DB.
VinayC