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