4

VS 2005 WinXP

I am writing an application that will connect to a samba share.

However, in my path I am getting an compile error:

unrecognized escape sequence

The path I am using is this:

string path = "\\Samba\sun005\admin_config\test.txt";

I have also tried the following using double backlashes:

string path = "\\Samba\\sun005\\admin_config\\test.txt";

However, the above compiles ok, but when it runs it complains "cannot find the path"

Also tried the following:

string path = @"\\Samba\sun005\admin_config\test.txt";

When I check in the debugger I get the following string

\\Samba\\sun005\\admin_config\\test.txt

I get access denied in my exception. Now that I am thinking about it. I haven't set the username and password. I think that is my problem.

phuclv
  • 37,963
  • 15
  • 156
  • 475
ant2009
  • 27,094
  • 154
  • 411
  • 609
  • 2
    What error are you getting with the last line (with the `@`)? It seems to be the right way to go. – BoltClock Jul 21 '10 at 02:46
  • I think you are right. I didn't set the username and password. I will report back if there is still some problem. – ant2009 Jul 21 '10 at 02:53
  • 2
    I assume you have a server named `Samba` and a share named `sun005` with directory `admin_config` and file `test.txt`. `"\\\\Samba\\sun005\\admin_config\\test.txt"` probably should work. – sarnold Jul 21 '10 at 02:54

2 Answers2

13

A UNC path should just include the machine name, the share name, an the path relative to the share point (inclusion of a "samba" scheme is not necessary). In the case of the machine name being sun005, either of the two following should work:

"\\\\sun005\\admin_config\\test.txt"
@"\\sun005\admin_config\test.txt"
Andy Hopper
  • 3,618
  • 1
  • 20
  • 26
  • It tells the C# compiler to interpret the string as a literal (i.e., don't use the \ character as an attention sequence for escape codes) – Andy Hopper Nov 19 '14 at 19:52
5

The compiler sees \\Samba\sun005\admin_config\test.txt as \Samba\sun005\x07dmin_config\x09est.txt. But it just doesn't understand the '\s'.

It sees \\Samba\\sun005\\admin_config\\test.txt as \Samba\sun005\admin_config\test.txt which the compiler is happy with, but you really need the two slashes at the start. For that you need to use four slashes "\\Samba...."

@"\\Samba\sun005\admin_config\test.txt" is exactly what you want! You see the extra slashes in the debugger, because the debugger it adding them, so you can see what is really in the string. If you had a newline character in the string, it would display as '\n'.

James Curran
  • 101,701
  • 37
  • 181
  • 258