0

I just wondering what is the best way to join domain name and username

for instance :

string domainName = @"DTS\";
string username = "jake";

string domainUser = domainName + usernName;

Please advise

Robert Groves
  • 7,574
  • 6
  • 38
  • 50
Supermode
  • 924
  • 3
  • 32
  • 53
  • `string domainName ="DTS\"` This is a compile error. – ta.speot.is Sep 27 '13 at 02:34
  • Don't fall in to the [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)! Ask us about your real enviorment, because as-is the answer to your question would be "do it excatly how you have it" due optimizing the entire thing would just turn in to `string domainName = @"DTS\"; string username ="jake"; string domainUser = @"DTS\jake";` – Scott Chamberlain Sep 27 '13 at 02:34

3 Answers3

4

You can do it as Stay Foolish has recommended.

If you want to use the currently logged in user, instead of hard coding the user, you can use Environment.UserDomainName and Environment.UserName

string domainUser = String.Format(
    @"{0}\{1}", 
    Environment.UserDomainName, 
    Environment.UserName);
Community
  • 1
  • 1
Robert Groves
  • 7,574
  • 6
  • 38
  • 50
0

Use:

string.format(@"{0}\{1}", domainName, userName)

In that case you don't need to put the '\' in the domain name.

Robert Groves
  • 7,574
  • 6
  • 38
  • 50
Stay Foolish
  • 3,636
  • 3
  • 26
  • 30
  • 2
    You need to preface the format string with `@` otherwise the `\\` will be treated as an escape – debracey Sep 27 '13 at 02:34
  • 2
    There is no "memory leak" in the normal sense of that phrase when concatenating strings. Your example allocates one string, concatenating two strings allocates one string. Even if there were more strings there would still be no "memory leak" just more allocations that get garbage collected. Also worth nothing that for constants the compiler will concatenate them at compile time. – Ian Mercer Sep 27 '13 at 03:00
0

string domainName = @"DTS\";

Or

string domainName = "DTS\\";

Robert Groves
  • 7,574
  • 6
  • 38
  • 50
Whitesmell
  • 204
  • 2
  • 13