2

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
broadband
  • 3,266
  • 6
  • 43
  • 73
  • 2
    Check [this](https://stackoverflow.com/a/38428899/1955268) answer which recommends using `Path.DirectorySeparatorChar` for better portability. – prinkpan Feb 28 '19 at 07:53

3 Answers3

2

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.

Chris Ruck
  • 391
  • 3
  • 4
2

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

private readonly string X86DllPath = Path.GetFullPath("x86/ShaferFilechck.dll");
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Hm didn't know that it constructs full absolute path with correct backslashes added. Thank you, this doesn't answer my question, but new thing has been discovered and partially answers my question. – broadband Feb 28 '19 at 09:56
0

There shouldn't be a problem using single forward slashes to express a network path, and I've never seen them converted to backward slashes.
Since you're new to C#, using single backslash characters can cause problems, because they may be treated as escape characters such as "\n" which is a newline character. If you're not intending to use backslash as an escape, you have two choices to force the system to use them as such: 1) use double slashes to separate the network path nodes 2) use the @ before a string that contains backward slashes. This is the cleaner way to go.

Romel Evans
  • 69
  • 10