9

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,

Ahmed
  • 14,503
  • 22
  • 92
  • 150
  • 1
    Take a look at [Path.GetInvalidFileNameChars](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx) and [Path.GetInvalidPathChars](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx) – Marlon Apr 10 '12 at 01:24
  • I've got a blog post covering how to write a WPF ValidationRule to validate this very thing, it's got a bunch of code you can rip from it: [*Taking data binding, validation and MVVM to the next level - part 2*](http://techfilth.blogspot.co.nz/2011/07/taking-data-binding-validation-and-mvvm.html). I mention this because there can be a bunch of edge cases when dealing with path and file names. – slugster Apr 12 '12 at 00:25

4 Answers4

6

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
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
3

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

The characters you must now use are: ? < > | : \ / * "

    string PathFix(string path)
    {
        List<string> _forbiddenChars = new List<string>();
        _forbiddenChars.Add("?");
        _forbiddenChars.Add("<");
        _forbiddenChars.Add(">");
        _forbiddenChars.Add(":");
        _forbiddenChars.Add("|");
        _forbiddenChars.Add("\\");
        _forbiddenChars.Add("/");
        _forbiddenChars.Add("*");
        _forbiddenChars.Add("\"");

        for (int i = 0; i < _forbiddenChars.Count; i++)
        {
            path = path.Replace(_forbiddenChars[i], "");
        }

        return path;
    }

Tip: You can't include double-quote ("), but you can include 2 quotes (''). In this case:

    string PathFix(string path)
    {
        List<string> _forbiddenChars = new List<string>();
        _forbiddenChars.Add("?");
        _forbiddenChars.Add("<");
        _forbiddenChars.Add(">");
        _forbiddenChars.Add(":");
        _forbiddenChars.Add("|");
        _forbiddenChars.Add("\\");
        _forbiddenChars.Add("/");
        _forbiddenChars.Add("*");
        //_forbiddenChars.Add("\""); Do not delete the double-quote character, so we could replace it with 2 quotes (before the return).

        for (int i = 0; i < _forbiddenChars.Count; i++)
        {
            path = path.Replace(_forbiddenChars[i], "");
        }

        path = path.Replace("\"", "''"); //Replacement here
        return path;
    }

You'll of course use only one of those (or combine them to one function with a bool parameter for replacing the quote, if needed)

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
1

The correct answer of Nikhil Agrawal has some syntax errors.

Just for the reference, here is a compiling version:

public static string MakeValidFolderNameSimple(string folderName)
{
    if (string.IsNullOrEmpty(folderName)) return folderName;

    foreach (var c in System.IO.Path.GetInvalidFileNameChars())
        folderName = folderName.Replace(c.ToString(), string.Empty);

    foreach (var c in System.IO.Path.GetInvalidPathChars())
        folderName = folderName.Replace(c.ToString(), string.Empty);

    return folderName;
}
Community
  • 1
  • 1
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291