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


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
: 591 At:- 10/11/2020 3:06:02 PM
C# illegal characters in path

1 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))

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

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

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

Full Name *

Email *

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