0
votes

I have a .NET MVC application where I am building a virtual path using the below:

Path.Combine("~/Documents/", "application", "username");

The output from this is "~/Documents/application\\username". This causes an error when passed to a Telerik RadFileExplorer however if I manually build the path as "~/Documents/application/username" it works fine. The example above uses strings but the actual code is using variables.

I'd prefer not to use String.Replace if possible... Is there an alternative to Path.Combine that would produce this output? "~/Documents/application/username"

3

3 Answers

1
votes

Path.Combine adds the / for you, so you don't need to add it when combining the path.

Try like this: Path.Combine("~/Documents", "application", "username");

1
votes

There are a lot of alternatives for combining the a path (which is basically a string). you can use the $ - string interpolation and put the parameters like this: $"~/{Documents}/{application}/{username}" which is more readable than replace.

1
votes

edit: just saw Raziel's answer, which is probably much better/simpler.. Livio's comment is in general incorrect. That's only true if run on a Unix-based system. If run on a Windows system Path.Combine defaults to backslashes unless otherwise specified.

From the documentation of Path.Combine it only uses the forward slash if it's explicitly included in the path component. I would suggest writing a function for the latter two arguments that just appends a forward slash to the end (and maybe also ensures that there are no slashes at the beginning because that would cause them to be interpreted as absolute paths and overwrite everything before that).