An ability to set the current working path often comes in handy if a developer wants to be able to use relative paths instead of absolute paths in the code. In this tip, I explain how to set the current working path using VB.NET.
In the code, using relative paths is usually preferred because it simplifies the code. However, relative paths are interpreted in relation to the current working directory; therefore, changing the current working path to a needed location allows developers to use relative paths in the code.
In order to determine the current working path, I use the Directory object's GetCurrentDirectory method. And, to modify the current working path, I use the SetCurrentDirectory method of the Directory object. Additionally, you can utilize the Path object's GetFullPath method, which allows you to convert a relative path into an absolute path using the current working directory.
In this example, I initially display a current working directory (utilizing the GetCurrentDirectory method of the Directory class). Then I utilize the GetFullPath method and pass to it a file name (which in this case is text1.txt). The results of both actions are added to the listbox ListBox1 item by item. The next step is to modify the current working directory. I add an empty line to ListBox1 by adding empty quotes. Then I set the current working directory to "C:/temp". To do that, I utilize the SetCurrentDirectory method. After that, I utilize the GetFullPath method, passing to it the same file name, and the results of both actions are added to ListBox1 one by one.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!