Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to use slash for path in c# code

I've been using Linux for years and because of the habit, I added / (slash) instead of \ (backslash) for path to my c# code.

private const string X86DllPath = "x86/ShaferFilechck.dll"; // should use x86\\ShaferFilechck.dll
private const string X64DllPath = "x64/ShaferFilechck.dll";

[DllImport(X64DllPath, EntryPoint = "NalpLibOpen", CallingConvention = CallingConvention.Cdecl)]
private static extern int NalpLibOpen_64(byte[] xmlParms);

The code works, but I'm wondering if c# translates slash to backslash when compiled and run on Windows. Is there some official documentation stating this or something.

Could using / in path result in some unexpected behaviour under some circumstances.

Update:

I know the ultimate solution would be to use this, but I'm wondering why slash is still 'ok':

Path.Combine("x86", "ShaferFilechck.dll"); // x86\ShaferFilechck.dll
like image 733
broadband Avatar asked Oct 30 '25 05:10

broadband


2 Answers

In my experience Windows is tolerant of using forward and back slashes as path separators. Even mixing them works. C# and .NET doesn't do any processing of any forward slashes in file names. Windows at the file system layer accepts them as an alternate character to the back slash. The same cannot be said of running C# code on Linux and other OS's.

For platform consistency it's not recommended to assume path separator. Your programs should use the Path.DirectorySeparatorChar to determine the proper character to use when deploying apps on different platforms.

See How can I create files on Windows with embedded slashes, using Python? for more info.

like image 179
Chris Ruck Avatar answered Nov 01 '25 18:11

Chris Ruck


You can probably use Path.GetFullPath() like below under System.IO namespace

private readonly string X86DllPath = Path.GetFullPath("x86/ShaferFilechck.dll");
like image 34
Rahul Avatar answered Nov 01 '25 17:11

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!