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
: 49 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))
  .ToArray());

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

0
At:- 10/11/2020 3:44:36 PM






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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly