Error "illegal characters in path" C#


Hello, I am trying to save file in C#, using file.SaveAs(Path), and getting the error "Illegal Characters in Path" as shown below

illegal-characters-in-path-c-sharp-min.png

When Saving file, it contains the file name, which can have any special characters like "-,+,',/,_,@,!" etc or even space inside the file name. So How can I save file without getting any error?


Asked by:- bhanu
0
: 8554 At:- 10/11/2020 3:06:02 PM
C# illegal characters in path







2 Answers
profileImage Answered by:- vikas_jk

You can simply use C# inbuilt function "Path.GetInvalidFileNameChars()" to check if there is invalid character in file name and remove it.

so, simply your C# code would be as below

var InvalidCharacters= Path.GetInvalidFileNameChars();

string GetInvalidCharactersRemovedString= new string(fileName
  .Where(x => !invalidChars.Contains(x))
  .ToArray());

Once the Invalid Characters are removed, now you can use the above string name, "GetInvalidCharactersRemovedString" to save file in a path.

1
At:- 10/11/2020 3:44:36 PM
Never know there is a method named "GetInvalidFileNameChars" to check illegal characters. 0
By : bhanu - at :- 11/12/2020 3:46:01 PM


profileImage Answered by:- bhanu

We can also use Linq to clean file names, here is extended method

private static string removeInvalidChar(string fileName)
{
    return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}

OR 

You can also simply replace illegal characters by "_"

public string RemoveInvalidChars(string filename)
{
    return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));    
}
0
At:- 5/24/2021 10:13:22 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use