-2

I have a program that mass creates directories based on a CSV file. It runs through the loop but then it hits an "invalid characters in path" I need a validation (or if statement) to validate the folderName first and if it's invalid -reports it in a log file, then just proceed with the next folder creation.

StreamWriter sw = new StreamWriter(targetdir + "log.txt");

try
{
    string[] items = File.ReadAllLines(csv);

    foreach (string item in items)
    {
        Directory.CreateDirectory(targetdir + item);
        sw.WriteLine(item + " OK!");                    
    }                

    MessageBox.Show("Done");
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

sw.Close();

I'm not sure where to start. I feel like i have to add an "if else" but i'm not sure what to put. Thanks in advance.

Nico Schreiner
  • 397
  • 5
  • 13
Poe
  • 13
  • 3

1 Answers1

3

The main change you need to do in your code is stopping concatenating together the variables that creates the destination folder and start using the Path.Combine method. In your specific case you could use GetInvalidFileNameChars to have a list of characters not allowed to be part of a path or file name and then check if the current item contains any of those characters.

But there are other important changes to do.
First a StreamWriter is a disposable object and thus you should always create it inside a using statement to have a correct cleaup of its internal resources when you have done with it or even if an abnormal exception occurs.
Second, it is better to use File.ReadLines instead of loading all the lines in memory with ReadAllLines

char[] invalidChars = Path.GetInvalidFileNameChars();
string logFile = Path.Combine(targetdir, "log.txt");
try
{
   using(StreamWriter sw = new StreamWriter(logFile))
   {
       foreach (string item in File.ReadLines(csv))
       {
           if(item.Any(x => invalidChars.Contains(x)))
                sw.WriteLine(item + " BAD");
           else
           {
                Directory.CreateDirectory(Path.Combine(targetdir,item));
                sw.WriteLine(item + " OK!");                    
           }
       }
    }                
    MessageBox.Show("Done");
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

Finally, I want to underline that in this context it is important to use GetInvalidFileNameChars and not GetInvalidPathChars because here we are checking the name of a folder. This name has the same rules used for files.
GetInvalidPathChars omits some characters that are valid in a path string like the \ or the ? and *. So for example GetInvalidPathChars doesn't have any issues with something like C:\Windows\System32\*.dll while this string contains characters not usable for a filename or for a single folder's name.

Steve
  • 213,761
  • 22
  • 232
  • 286