0

I check a file name validation in the following way:

foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
    validFileName = validFileName.Replace(c, '_');
} 

Is there a faster way do do so?

2 Answers 2

1

This might be faster, but I hardly think the original would be slow enough to care about...

var invalidChars = Path.GetInvalidFileNameChars();
var fileNameChars = validFileName.ToCharArray();

for (int i = 0; i < fileNameChars.Length; ++i)
    if (invalidChars.Contains(fileNameChars[i]))
        fileNameChars[i] = '_';

validFileName = new string(fileNameChars);
Sign up to request clarification or add additional context in comments.

4 Comments

Any reason you increment the index with ++i, instead of i++?
@RandRandom Force of habit from olden C++ days where ++i could be more efficient than i++. Makes no difference either way for C# in this usage due to optimizations, of course. But at least I know I'm being precise about whether I need the value before incrementing or not (++i is clear that I don't)
But wouldnt this for loop, skip the fileNameChars[0], because the ++ infront of the i means that you do the increment before you get the value? does this code reach 0. - yeah I know I could test it, but no IDE close by :)
@RandRandom No, it doesn't increment it before the start of the loop. It's just executed at the end of each loop iteration, so it doesn't make any difference whether you use ++i or i++. See here for full definition.
1

Whats wrong with that? Two line implementation, and a stack overflow search for this shows your answer matches an accepted answer for another question How to make a valid Windows filename from an arbitrary string?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.