5

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.

2
  • When entering code you need to select it and use the code icon (101010) to preserve original formatting. Commented May 22, 2010 at 20:01
  • 1
    It would help if you gave an example of what you want the end result to look like. Commented May 22, 2010 at 20:53

3 Answers 3

20

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

Sign up to request clarification or add additional context in comments.

1 Comment

You'll want to remove the slashes from folderName as well though: string folderName = "AlarmLogger";
2

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.