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?
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly