Latest .NET (Core) versions, that run on Windows and Linux, support paths handling on both formats, depending on where the application is running.
The problem is, although it supports dealing with Windows paths if running on Windows and dealing with Linux paths if running on Linux, I see no way of specifying the format of the path I want to manipulate.
For instance, the following code:
string windowsPath = @"abc\xyz";
string linuxPath = @"abc/xyz";
Console.WriteLine("Windows file name: " System.IO.Path.GetFileName(windowsPath));
Console.WriteLine("Linux file name: " System.IO.Path.GetFileName(linuxPath));
produces the following result if running on Windows:
Windows file name: xyz
Linux file name: xyz
and the following result if running on Linux:
Windows file name: abc\xyz
Linux file name: xyz
Is it possible to, on an application running on Linux, tell System.IO.Path methods that I want to handle paths on Windows format? Something I would imagine it would be Path.GetFileName(windowsPath, OSPlatform.Windows)
or similar.
Or is there any NuGet package that allows this?
TLDR:
If I am running a .NET application on Linux and I want to handle paths with System.IO.Path that I know are in Windows format, is there a way to specify it? Or is there a NuGet package that allows this?
CodePudding user response:
If you got the Windows path string from somewhere and your application did not compose it by itself, replace the \
characters with /
characters before using the path string. There should be no need for some fancy-schmanzy library to do just that. However, this is only sufficient for "simple" relative paths.
However, Windows paths can be in the form of UNC paths or start with a drive letter. If it is possible that your application might be confronted with such paths, you need to determine a strategy for your application scenario of how to deal with them.
On the other hand, if your application itself composes those path strings, preferably use the System.IO.Path.Combine
method, or make use of the host OS-dependent directory path separator provided by System.IO.Path.DirectorySeparatorChar
.
CodePudding user response:
I'm a little unsure of your question. If you just want to make sure the path delimiter is correct for the platform it's running on then use Path.Combine which should do this automatically using platform-specific values of Path.PathSeparator
and Path.DirectorySeparatorChar
constants.
Instead of:
string windowsPath = @"abc\xyz";
string linuxPath = @"abc/xyz";
use:
using System.IO;
string anyPath = Path.Combine("abc", "xyz");
If you wanted to make a windows path while running on iOS for example then just use
path = path.Replace("/", @"\");