Escape for folder Exists and Create purposes

.net, c#

Solution

You don't need to check if subdirectories exist . `Directory.CreateDirectory` will create all subdirectories that you need. For more information check the documentation here.

Creates all directories and subdirectories in the specified path.

Moreover instead of concatening your strings with `@"\"`, the safer way is to use `Path.Combine`. E.g :

String yourFullPath = Path.Combine(
      @"C:\", 
      reader1.GetString(ColIndex1),  
      reader1.GetString(ColIndex2), 
      reader1.GetString(ColIndex3)); 

// following will do nothing if yourFullPath already exists
Directory.CreateDirectory(yourFullPath) ;

Finally, I've tried this sample with a `/` character :

System.IO.Directory.CreateDirectory(System.IO.Path.Combine(@"c:\", @"a/b\c")) ; 

And it's creating all the folders `a`, `b` and `c`.

EDIT

If you want to removeInvalidcharPath. Path.GetInvalidFileNameChars() will help you to do so :

char [] allInvalidChars = Path.GetInvalidFileNameChars(); 
string yourPathWithoutInvalidChars = new string(yourFullPath.ToCharArray().Where(c => !allInvalidChars.Contains(c)).ToArray());

Problem

I have the following code: ``` if (!Directory.Exists(@"C:\" + reader1.GetString(ColIndex1) + @"\" + reader1.GetString(ColIndex2) + @"\" + reader1.GetString(ColIndex3))) { Directory.CreateDirectory(@"C:\" + reader1.GetString(ColIndex1) + @"\" + reader1.GetString(ColIndex2) + @"\" + reader1.GetString(ColIndex3)); } ``` How do I escape the values so it can correctly check if folders exist and create them if needed? For example, at the moment, if ColIndex2 contains text which includes the following characters: ``` \/:*?"<>| ``` The code does not create the folders properly.

Original source