Search code examples
vb.netvisual-studio-2010

How do I get the 'Right' function to work with strings?


Basically, I'm trying to do some string manipulation to edit directories.

I found some code to try and edit the directories, but when I use it it doesn't recognise Right as being a function and only recognises it as a Right property, thus producing an error.

I was wondering if there's something I haven't imported or if perhaps Right is an obsolete function that was used in VB6 but replaced with something.

The code I have is as follows:

Dim Foo As String
Dim Bar As String
Bar = ' Some form of directory input e.g. My.Computer.CurrentDirectory
Foo = Right(Bar, (Len(Bar) - InStrRev(Bar, "/")))
MsgBox(Foo)

Ideally I need either a better method of manipulating directories or a way to get the Right functionality working.


Solution

  • but when I use it it doesn't recognise 'right' as being a function and only recognises it as a right property, thus producing an error.

    If you have a "right" property, you can fully qualify the function:

    Foo = Microsoft.VisualBasic.Right(Bar, (Len(Bar) - InStrRev(Bar, "/")))
    

    For details, see the docs for the Right Function.

    Note that, for directory parsing, you can handle this much more cleanly via the System.IO namespace. In particular, you can construct a DirectoryInfo and get the parent folder via the Parent property.

    You can also use Path.GetDirectoryName to work with strings. In your case, if you had Bar set to "C:\Some\Path\To\A\File.txt" and you call Path.GetDirectoryName(Bar), it will return "C:\Some\Path\To\A". If you call it on that, you'll get ""C:\Some\Path\To", etc.