简体   繁体   中英

Path.Combine not producing absolute paths

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?

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.

string rootPath = IsWindowsOS() ? "C:\" : "/";
string absolutePath = Path.Combine(rootPath, "etc", "blah");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM