Michael Schnerring
Michael Schnerring

Reputation: 3661

directory path as string: ensure DirectoryPathSeperator at the end of the string

Is there a method in .NET, which automatically appends a backslash at the end of a path which is a string?

Something like:

var path = @"C:\Windows";
path = Path.GetPathWithSeperatorAtTheEnd(path);
Console.WriteLine(path); 
// outputs C:\Windows\

What I currently do is:

if (!path.EndsWith(@"\")) path += @"\";

EDIT: What I'd like to achieve is, that if I append filenames to a path I don't need to worry about, that something like this happens. Or is there another approach than appending path and filename?

var fullFilename = path + filename;
// path    : C:\Windows
// filename: MyFile.txt
// result  : C:\WindowsMyFile.txt

Upvotes: 1

Views: 485

Answers (1)

CodingGorilla
CodingGorilla

Reputation: 19842

You can use: System.IO.Path.Combine

Example:

var path = @"C:\Windows";
path = Path.Combine(path, "win.ini");
// path is @"C:\Windows\win.ini"

Upvotes: 7

Related Questions