Use Path.Combine
Path.Combine
uses the Path.PathSeparator
and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.
Quoted from this SO post
Also it would be fruitful to check if you name
variable contains invalid characters for a filename.
You may first remove invalid characters from name
variable using Path.GetInvalidFileNameChars method :
var invalidChars = Path.GetInvalidFileNameChars();
string invalidCharsRemoved = new string(name
.Where(x => !invalidChars.Contains(x))
.ToArray());
Quoted from this SO post
string directory = "c:\\temp";
Instead of
File.Create(name + ".txt")
Use
string filename = invalidCharsRemoved + ".txt"
File.Create(Path.Combine(directory , filename ))