tags:

views:

95

answers:

3

So I'm trying to create a path in C#. I use Environment.Machinename and store it a variable serverName. Then I create another string variable and have some other path extension in there. Here is my code so far:

string serverName = Environment.MachineName;
string folderName = "\\AlarmLogger";

No matter what I do I can't seem to obtain only one backslash prior to AlarmLogger. Any ideas how I can specify a path in C#?

Edit: I'm wondering if my code doesn't seem to want to paste correctly. Anyways when i paste it I only see one backslash but my code has two. Because of the escape character sequence. But something like

string test = @"\\" + serverName + folderName 

doesn't seem to want to work for me.

+11  A: 

Use Path.Combine(serverName, folderName). Path.Combine is always a better solution than concating it on your own.

Femaref
I'll give that a shot. Thank you.
Jason
You'll want to remove the slashes from folderName as well though: string folderName = "AlarmLogger";
s1mm0t
+1  A: 

It's not clear what you are trying to do or what is going wrong.

If you are having trouble including backslashes in your strings, they need to be escaped with an extra backslash:

string twoBackslashes = "\\\\";

Or you can do it like this:

string twoBackslashes = @"\\";

If you are trying to manipulate paths, look at the System.IO.Path class. In particular, Path.Combine can be useful.

Daniel Plaisted
+1  A: 

You cannot use Path.Combine for this as suggested. The reason is that it ignores static variables if the first entry is static, e.g. Environment.MachineName (see MSDN docs for details). If you use Path.Combine(servername, foldername) you will get "\AlarmLogger". Plus, it parses double slashs to single slashes.

That being said, you can do something like the following (among other ways):

string serverName = Environment.MachineName;
string folderName = "\\\\AlarmLogger";  //this gives alarmlogger two leading slashes
string test = @"\\" + serverName + folderName.Substring(1,folderName.Length-1); //this removes one of the two leading slashes

You could use a slew of ways to remove the leading slash besides substring.

John