2

I want to replace these characters with string.Empty:'"<>?*/\| in given Filename How to do that using Regex I have tried this:

Regex r = new Regex("(?:[^a-z0-9.]|(?<=['\"]))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
                 FileName = r.Replace(FileName, String.Empty);

but this replaces all special characters with String.Empty.

Santhosh Nayak
  • 2,312
  • 3
  • 35
  • 65
  • 2
    http://mattgemmell.com/2008/12/08/what-have-you-tried/ – walther Aug 23 '12 at 09:59
  • possible duplicate of [How to remove illegal characters from path and filenames?](http://stackoverflow.com/questions/146134/how-to-remove-illegal-characters-from-path-and-filenames) – Nasreddine Aug 23 '12 at 10:15

2 Answers2

5

You could use the Regex.Replace method. It does what its name suggests.

Regex regex = new Regex(@"[\\'\\""\\<\\>\\?\\*\\/\\\\\|]");
var filename = "dfgdfg'\"<>?*/\\|dfdf";
filename = regex.Replace(filename, string.Empty);

But I'd rather sanitize it for all characters that are forbidden in a filename under the file system that you are currently using, not only the characters that you have defined in your regex because you might have forgotten something:

private static readonly char[] InvalidfilenameCharacters = Path.GetInvalidFileNameChars();

public static string SanitizeFileName(string filename)
{
    return new string(
        filename
            .Where(x => !InvalidfilenameCharacters.Contains(x))
            .ToArray()
    );
}

and then:

var filename = SanitizeFileName("dfgdfg'\"<>?*/\\|dfdf");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

look here how to do it:

How to remove illegal characters from path and filenames?

remember to use Path.GetInvalidFileNameChars()

Community
  • 1
  • 1
Stephan Schinkel
  • 5,270
  • 1
  • 25
  • 42