开发者

How do I ensure a file path is valid?

开发者 https://www.devze.com 2023-01-15 12:19 出处:网络
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:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消