I am trying to port some Python code to .NET, and I was wondering if there were equivalents of the following Python functions in .NET, or some code snippets that have the same functionality.
os.path.split()
os.path.basename()
Edit
os.path.basename() in Python returns the tail of os.path.split, not the result of System.IO.Path.GetPathRoot(path)
I think the following method creates a suitable port of the os.path.split function, any tweaks are welcome. It follows the description of os.path.split from http://docs.python.org/library/os.path.html as much as possible I believe.
public static string[] PathSplit(string path)
{
string head = string.Empty;
string tail = string.Empty;
if (!string.IsNullOrEmpty(path))
{
head = Path.GetDirectoryName(path);
tail = path.Replace(head + "\\", "");
}
return new[] { head, tail };
}
I’m unsure about the way I’m returning the head and tail, as I didn’t really want to pass out the head and tail via parameters to the method.
os.path.basename()
The alternative isSystem.IO.Path.GetPathRoot(path);:Edit: The above returned the first path of the path, where
basenameshould return the tail of the path. See the code below for an example of how this could be achieved.os.path.split()
Unfortunately there’s no alternative to this as there’s no .Net equivalent. The closest you can find is
System.IO.Path.GetDirectoryName(path), however if your path was C:\Foo, thenGetDirectoryNamewould give you C:\Foo instead of C: and Foo. This would only work if you wanted to get the Directory Name of an actual file path.So you’ll have to write some code like the following to break these down for you: