00 Votes

C#/.NET: Ensure Backslash at End of Path

Question by CSchaf | 2014-09-01 at 21:55

In my program, I have a string containing the path to directory (for example C:\Folder\). Later, I would like to create a full file path from this string (for example C:\Folder\File.txt).

To make that succeed, of course, I have to ensure, that there is a backslash (\) at the end of the directory-string, because otherwise, the resulting file path would be wrong, for example C:\FolderFile.txt or something like that.

From other programming languages, I know functions such as IncludeTrailingBackslash or IncludeTrailingPathDelimiter. Is there anything similar also in C# (C-Sharp, .NET Framework)?

ReplyPositiveNegativeDateVotes
2Best Answer2 Votes

I do not know any standard function to do this directly.

However, I think, the following method can help you:

string pfad = @"C:\Folder";

pfad.TrimEnd("\\") + "\\".

With TrimEnd, you are removing the backslash that is possibly at the end of your string. After that, you are appending a new backslash to the string.

So, if your path have not had any backslash at the end at the beginning, TrimEnd is doing nothing and in each case, afterwards, there will be a backslash at the end of the string.

By the way, instead of "\\", you could also use the constant stored in Path.DirectorySeparatorChar because the path delimiter is not always the backslash on each operating system
2014-09-02 at 19:15

ReplyPositive Negative
22 Votes

You can also just write:

Path.Combine("string1", "string2", "string3"...); 

With this, the path separators will be set automatically.
2016-11-06 at 14:13

ReplyPositive Negative
Reply

Related Topics

Rename File to its Folder Name

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.