Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how can I prepare a string to be valid for windows directory name

Tags:

c#

I am writing a C# program which reads certain tags from files and based on tag values it creates a directory structure.

Now there could be anything in those tags,

If the tag name is not suitable for a directory name I have to prepare it to make it suitable by replacing those characters with anything suitable. So that directory creation does not fail. I was using following code but I realised this is not enough..

path = path.replace("/","-");
path = path.replace("\\","-");

please advise what's the best way to do it..

thanks,

like image 661
Ahmed Avatar asked Apr 10 '12 01:04

Ahmed


2 Answers

Import System.IO namespace and for path use

Path.GetInvalidPathChars

and for filename use

Path.GetInvalidFileNameChars

For Eg

string filename = "salmnas dlajhdla kjha;dmas'lkasn";

foreach (char c in Path.GetInvalidFileNameChars())
    filename = filename.Replace(System.Char.ToString(c), "");

foreach (char c in Path.GetInvalidPathChars())
    filename = filename.Replace(System.Char.ToString(c), "");

Then u can use Path.Combine to add tags to create a path

string mypath = Path.Combine(@"C:\", "First_Tag", "Second_Tag"); 

//return C:\First_Tag\Second_Tag
like image 142
Nikhil Agrawal Avatar answered Sep 29 '22 11:09

Nikhil Agrawal


You can use the full list of invalid characters here to handle the replacement as desired. These are available directly via the Path.GetInvalidFileNameChars and Path.GetInvalidPathChars methods.

like image 34
Reed Copsey Avatar answered Sep 29 '22 10:09

Reed Copsey