0

I have some code running on Linux with Mono and I am trying to create paths which will then be passed to some file IO methods.

I'm finding that if I want to specify the root (eg: /etc/blah instead of /MyApplication/etc/blah) I have to do the following:

Directory.GetFiles(Path.Combine("/etc", "blah"))

However as you can see I have to manually specify that the first part is an absolute path with the /. This defeats the purpose of the Path.Combine. I looked at the documentation for an overload to specify if it should be a relative or absolute path but there isn't one.

How do I correctly specify an absolute path?

user9993
  • 5,833
  • 11
  • 56
  • 117
  • http://stackoverflow.com/questions/372865/path-combine-for-urls – MethodMan Jan 18 '16 at 21:16
  • Do you always need to combine with /etc or any root directory? – Rahul Jan 18 '16 at 21:16
  • As per the MSDN documentation, this is operating as designed. What comes out of `Path.Combine` is relative paths if you didn't specify that it's a root path, you have to specify that it's a root path. What did you expect? – willaien Jan 18 '16 at 21:16

2 Answers2

1

Path.Combine is not designed to produce absolute paths. The path returned will be absolute if and only one of the arguments is absolute.

Path.Combine is designed to combine paths. It can combine two relative paths to make a new relative path. For instance:

string path = Path.Combine("foo", "bar");
// path is now "foo/bar", a relative path

In other words, the function behaves as designed and if you wish to produce an absolute path, provide an absolute path for the first argument.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
-1
string rootPath = IsWindowsOS() ? "C:\" : "/";
string absolutePath = Path.Combine(rootPath, "etc", "blah");
knocte
  • 16,941
  • 11
  • 79
  • 125
  • Considering that Windows has potentially more drives than just one, hardcoding `C:\` is probably not terribly useful. Then there's also things like UNC paths ... – Joey Sep 13 '18 at 16:11