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)?
Related Topics
HTML5 Canvas: Beginner Tutorial Chapter 3 - Rectangles and Circles
Tutorial | 0 Comments
Rename File to its Folder Name
Tutorial | 0 Comments
HTML5 Canvas: Beginner Tutorial Chapter 2 - Drawing Lines
Tutorial | 0 Comments
JavaScript: Multiline Strings in Source Code
Tip | 0 Comments
Delphi: Read out folder of our own application
Tip | 0 Comments
Windows Tip: Copy full File Path using the Context Menu
Tip | 0 Comments
Lazarus: Open File or Document platform-independent
Tip | 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.
I do not know any standard function to do this directly.
However, I think, the following method can help you:
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
You can also just write:
With this, the path separators will be set automatically.
2016-11-06 at 14:13