getting just profile name from profile path

Darren Rose 281 Reputation points
2020-12-03T21:15:44.847+00:00

Hi

I have a list of profile paths, and I want to remove the c:\users\ and just keep the profile name

Things to consider - if run on a computer with a different language then I assume it is not always called c:\users\

The list of profiles are not all profiles on machine I am working on, so need to work from the strings I have rather than obtaining the profile names from registry etc

so

C:\users\dave

would return

dave

C:\users\clive_w

would return

clive_w

What is the best way to achieve this reliably taking into account the fact c:\users\ could be something like C:\Benutzer\ on a german computer ? (n.b. I don't know, I am just assuming Windows changes name of common folders to match the language used)

Thanks

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,741 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 118.2K Reputation points
    2020-12-03T21:45:04.46+00:00

    Try the approach that is shown in this example:

    Dim folder1 As String = "C:\users\dave"
    Dim folder2 As String = "C:\something\else"
    
    Dim u = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
    
    If Path.GetDirectoryName(folder1).Equals(u, StringComparison.CurrentCultureIgnoreCase) Then
        Dim name = Path.GetFileName(folder1)
        Console.WriteLine(name)
    End If
    
    If Path.GetDirectoryName(folder2).Equals(u, StringComparison.CurrentCultureIgnoreCase) Then
        Dim name = Path.GetFileName(folder2)
        Console.WriteLine(name)
    End If
    
    0 comments No comments

  2. Darren Rose 281 Reputation points
    2020-12-03T21:49:56.543+00:00

    Hi Viorel-1

    Thanks. Yes that works fine for me in UK with C:\Users - not got a computer running another language so can't test that though.

    So what I need is to convert it into a function, so I pass it the full path e.g. "C:\users\dave" and it returns me "dave"

    and then I will find a computer running another language to ensure my app won't then fail if run when profile path don't start with c:\users\ and it will just cope with whatever the c:\users\ is called

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.