Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert DOMAIN\USER to USER@DOMAIN

Tags:

c#

I currently have the following code:

string user = @"DOMAIN\USER";
string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None);
string user = parts[1] + "@" + parts[0];

Input string user can be in one of two formats:

DOMAIN\USER
DOMAIN\\USER (with a double slash)

Whats the most elegant way in C# to convert either one of these strings to:

USER@DOMAIN
like image 636
general exception Avatar asked Aug 03 '12 14:08

general exception


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


3 Answers

Not sure you would call this most elegant:

string[] parts = user.Split(new string[] {"/"},
                            StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}@{1}", parts[1], parts[0]);
like image 79
Oded Avatar answered Oct 07 '22 01:10

Oded


How about this:

        string user = @"DOMAIN//USER";
        Regex pattern = new Regex("[/]+");
        var sp = pattern.Split(user);
        user = sp[1] + "@" + sp[0];
        Console.WriteLine(user);
like image 21
Mithrandir Avatar answered Oct 07 '22 00:10

Mithrandir


A variation on Oded's answer might use Array.Reverse:

string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(parts);
return String.Join("@",parts);

Alternatively, could use linq (based on here):

return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
       .Aggregate((current, next) => next + "@" + current);
like image 31
Jon Egerton Avatar answered Oct 06 '22 23:10

Jon Egerton