Home > OS >  Weird behaviour by System.IO.Path.Combine()
Weird behaviour by System.IO.Path.Combine()

Time:11-11

Console.WriteLine(System.IO.Path.Combine("C:\\some\\path\\", "this\\folder\\")); when run in microsoft's try-dotnet page, returns C:\some\path\/this\folder\.

I expect it to return C:\some\path\this\folder\.

How to fix this?

EDIT: In dotnetfiddle.net, however, I get the expected result. But I am worried because the official try-dotnet returns unexpected result.

CodePudding user response:

This is an example from https://docs.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-5.0

The problem with try-dotnet is that it is Unix-based system.

string[] paths = {@"d:\archives", "2001", "media", "images"};
string fullPath = Path.Combine(paths);
Console.WriteLine(fullPath);            

paths = new string[] {@"d:\archives\", @"2001\", "media", "images"};
fullPath = Path.Combine(paths);
Console.WriteLine(fullPath); 

paths = new string[] {"d:/archives/", "2001/", "media", "images"};
fullPath = Path.Combine(paths);
Console.WriteLine(fullPath); 
// The example displays the following output if run on a Windows system:
//    d:\archives\2001\media\images
//    d:\archives\2001\media\images
//    d:/archives/2001/media\images
//
// The example displays the following output if run on a Unix-based system:
//    d:\archives/2001/media/images
//    d:\archives\/2001\/media/images
//    d:/archives/2001/media/images

CodePudding user response:

you can declare the path to a variable before print out or use the value of the path

var fullPath = "C:\\some\\path"   "this\\folder\\";
Console.WriteLine(System.IO.Path.GetFileName(fullPath));
  • Related