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?

user3165438
  • 2,631
  • 7
  • 34
  • 54

2 Answers2

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?

Community
  • 1
  • 1
DLeh
  • 23,806
  • 16
  • 84
  • 128
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);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Any reason you increment the index with `++i`, instead of `i++`? – Rand Random Mar 10 '14 at 12:45
  • @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) – Matthew Watson Mar 10 '14 at 13:12
  • 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 :) – Rand Random Mar 10 '14 at 14:26
  • @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](http://msdn.microsoft.com/en-us/library/ch45axte.aspx) for full definition. – Matthew Watson Mar 10 '14 at 15:13