# VBForums CodeBank > CodeBank - Visual Basic .NET >  VB.NET - Correct method for app.path

## techyspecy

Geez, Its been a pain in the freakin ass to get application path in .NET. Here you go buddy's


VB Code:
Private Function GetAppPath() As String
        Dim l_intCharPos As Integer = 0, l_intReturnPos As Integer
        Dim l_strAppPath As String
         l_strAppPath = System.Reflection.Assembly.GetExecutingAssembly.Location()
         While (1)
            l_intCharPos = InStr(l_intCharPos + 1, l_strAppPath, "\", CompareMethod.Text)
            If l_intCharPos = 0 Then
                If Right(Mid(l_strAppPath, 1, l_intReturnPos), 1) <> "\" Then
                    Return Mid(l_strAppPath, 1, l_intReturnPos) & "\"
                Else
                    Return Mid(l_strAppPath, 1, l_intReturnPos)
                End If
                Exit Function
            End If
            l_intReturnPos = l_intCharPos
        End While
    End Function

----------


## lcdial

Good work!!! Is there anything I miss if I do it like this:


VB Code:
Private Function GetAppPath() As String
        Dim i As Integer
        Dim strAppPath As String
        strAppPath = System.Reflection.Assembly.GetExecutingAssembly.Location()
        i = strAppPath.Length - 1
        Do Until strAppPath.Substring(i, 1) = "\"
            i = i - 1
        Loop
        strAppPath = strAppPath.Substring(0, i)
        Return strAppPath
End Function

----------


## Merrion

You should use *System.IO.Path* to strip the filename from the path...e.g.


VB Code:
Return System.IO.Path.GetDirectory(System.Reflection.Assembly.GetExecutingAssembly.Location())

----------


## Redth

This seems to work too, however there might be something improper about it, if there is something wrong with it, I'd like to hear why it shouldn't be done this way, but here it is:


VB Code:
AppDomain.CurrentDomain.BaseDirectory

----------


## vbgladiator

Application.StartupPath()  also seems to do the job.

----------


## MrPolite

> _Originally posted by vbgladiator_ 
> *Application.StartupPath()  also seems to do the job.*


 just wanted to say that is what I also use all the time (since it's the simplest of all). I don't know if it makes a big difference, but all these methods seem to work fine. so why not pick application.startuppath? it's just the most straightforward of all  :Wink:

----------


## hellswraith

Agreed.  It seems like people make this harder than what it is.  Application.StartupPath works perfectly for me also.

----------


## Sisyphus

VB Code:
dim AppPath as string
AppPath = Environment.CurrentDirectory()
that also works smoothly.

----------


## MrPolite

> _Originally posted by Sisyphus_ 
> *
> VB Code:
> dim AppPath as string
> AppPath = Environment.CurrentDirectory()
> that also works smoothly.*


 noooooooooo I dont think it's a good idea to use that. I *think* that currentDirectory can change while your app is running

----------


## Libero

Hoho, try this.

VB Code:
MsgBox(CurDir)
And if you are going to pen a file in your apppath.

VB Code:
Dim file As New System.IO.StreamReader("test.txt")
        TextBox1.Text = file.ReadToEnd()
        file.Close()

----------


## MrPolite

> _Originally posted by Libero_ 
> *Hoho, try this.
> 
> VB Code:
> MsgBox(CurDir)
> And if you are going to pen a file in your apppath.
> 
> VB Code:
> Dim file As New System.IO.StreamReader("test.txt")
> ...


 your second method won't always work if I'm not mistaken (because current directory can change  :Smilie:  )
plus CurDir is a VB compatibility thing, better not to use it

----------


## vbjay

Also try creating a shortcut to your exe and set the start in property to some other path.

Use application.startuppath.

----------


## Dasiths

Hi,
I dunno about vb.net but in vb6 app.exename can change in windows xp if you start the program using the shell with the short directory name.

I use GetSetting(app.exename,..)

it changes when i use the short pathname to launch my program.

----------


## dtp1000

This C# function can be useful in a library for implementation of a MVC pattern or anything else. 
Traduction to VB is simple. 
Assert line is optional.



```

/// <summary>
/// Get the current path of the executing assembly.
/// ex : If this function currently executed in this library "C:\MyProgram\MyLibrary.dll",
/// this function will return "C:\MyProgram\"
/// </summary>
/// <returns></returns>
private static string GetExecutingAssemblyDirectory()
{

      string currentAssembly = Assembly.GetExecutingAssembly().Location; // Get current assembly with filename
      int nbCharToKeep = currentAssembly.Length;                         // Initialize length

      // Decrease length until an escape caracter is found
      while (currentAssembly[nbCharToKeep - 1] != '\\')
      {
           nbCharToKeep--;
           System.Diagnostics.Debug.Assert(nbCharToKeep >= 0, "GetExecutingAssemblyDirectory() - nbCharToKeep < 0");
      }

      // Return the dir including the last escape
      return currentAssembly.Substring(0, nbCharToKeep);

}
```

----------


## JuggaloBrotha

this whole thread can be replaced with one line:
Application.StartupPath

----------


## dtp1000

Microsoft says :



> Application.StartupPath Property  
> *Gets the path for the executable file that started the application*, not including the executable name.


So, this only works if your library is in the same application path. To avoid coupling a library with a particular application file, I do not recommand to use it in a dll.

 :wave:

----------


## cits

```
My.Application.Info.DirectoryPath
```

works for me in VB 2008

----------


## Kallog

> Application.StartupPath()  also seems to do the job.


This doesn't work if the application is an ActiveX server being called by a client such as Excel. Then it returns the path to the client application instead.

----------


## JuggaloBrotha

> This doesn't work if the application is an ActiveX server being called by a client such as Excel. Then it returns the path to the client application instead.


An ActiveX DLL is just a regular .Net DLL that has an Interface that wraps it for COM objects.  To get the DLL's path it looks like you can use: AppDomain.CurrentDomain.BaseDirectory, but if you need the word/excel/whatever path, I think you'll have to have a method or property that the COM object can set, your DLL & .Net wont know where it is unless it's told (passed in manually) where it is.

----------


## Kallog

> Then it's not a .Net app and thus has nothing to do with this vb.net codebank


Huh? I did that with Visual Basic 2008 Express which can create OLE Automation servers. If it wasn't a .Net app I wouldn't be able to call the .Net function Application.StartupPath().

Anyway I found the other common reply:


```
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location())
```

to correctly give the application exe's directory even when called through COM/ActiveX/OLE automation/whatever you call it.

----------


## Kallog

> Then it's not a .Net app and thus has nothing to do with this vb.net codebank


Feel free to apologize for your offensively worded mistake.

----------


## rcook

I'm a relative Visual Studio/VB .net newbie, though experienced in other languages and technologies.  This is an interesting thread, not least because of all the effort put in so far that still doesn't answer my particular question.

I am writing a VB .NET web application in visual studio 2008.  I want to execute an external program to perform a function for the user, so I need to put the executable somewhere that is independent of its installation machine and accessible by my code.  It would seem to make sense to put it in the same place as the EXE and DLL files containing the web application, but I don't know how to access it after that.

Many of the answers given in this thread and other places so far don't seem to fit my environment.  If I type "My." into my Visual Studio editor, for instance, it gives me Computer and User, but not Application, as options, so I gather I cannot use My.Application for anything.  

Likewise, if I type "Application.s" into the editor, it gives me "Set" and "StaticObjects" as options, but no "Startup" or "Startup()".

Environment.CurrentDirectory gives C:\Windows\system32 at runtime in my development environment; that's not it.


System.Reflection.Assembly.GetExecutingAssembly.Location() gives C:\Users\username\AppData\Local\Temp\Temporary ASP.NET Files\root\fe508d91\60a8c65a\assembly\dl3\b72b7ebd\60f25a6c_b1c2ca01\WebApplication2.DLL at runtime, so that's not it either.

AppDomain.CurrentDomain.BaseDirectory gives C:\Users\username\Documents\Visual Studio 2008\Projects\WebApplication2\WebApplication2\ at runtime in my development environment, and that seems to hold the most promise.  Is this one right?  If I use that, can I (somehow) package my little executable with my web application and run it from that directory?  And if the answer to that is yes, is there some magic to putting that executable in that directory?

It is extraordinary that it takes this much effort to find this out.  Why does my Big Fat Visual Basic 2008 book explicitly say that I can use My.Application, but Intellisense in Visual Studio 2008 doesn't recognize it?

----------


## Kallog

> System.Reflection.Assembly.GetExecutingAssembly.Location() gives C:\Users\username\AppData\Local\Temp\Temporary ASP.NET Files\root\fe508d91\60a8c65a\assembly\dl3\b72b7ebd\60f25a6c_b1c2ca01\WebApplication2.DLL at runtime, so that's not it either.


It looks like that dll is your program yea? I don't have a clue about web applications, but however you got WebApplication2.dll into that folder, can't you do the same thing to put the .exe there too?





> It is extraordinary that it takes this much effort to find this out.  Why does my Big Fat Visual Basic 2008 book explicitly say that I can use My.Application, but Intellisense in Visual Studio 2008 doesn't recognize it?


It may need a reference to be added. Type in the my.application call and use the mouseover dropdown box of 'error correction options'.

----------


## JuggaloBrotha

> I'm a relative Visual Studio/VB .net newbie, though experienced in other languages and technologies.  This is an interesting thread, not least because of all the effort put in so far that still doesn't answer my particular question.
> 
> I am writing a VB .NET web application in visual studio 2008.  I want to execute an external program to perform a function for the user, so I need to put the executable somewhere that is independent of its installation machine and accessible by my code.  It would seem to make sense to put it in the same place as the EXE and DLL files containing the web application, but I don't know how to access it after that.
> 
> Many of the answers given in this thread and other places so far don't seem to fit my environment.  If I type "My." into my Visual Studio editor, for instance, it gives me Computer and User, but not Application, as options, so I gather I cannot use My.Application for anything.  
> 
> Likewise, if I type "Application.s" into the editor, it gives me "Set" and "StaticObjects" as options, but no "Startup" or "Startup()".
> 
> Environment.CurrentDirectory gives C:\Windows\system32 at runtime in my development environment; that's not it.
> ...


WebApp's don't have access to the local system like WinForm's apps do.  This is why you don't have an Application.StartupPath, because if you did, it's the location on the web server, not the person's local machine who's viewing your site in their web browser.  When you're developing the webapp AppDomain.CurrentDomain.BaseDirectory returns the path to the project on your local computer because your computer is the web server, all be it a fake one, but one nonetheless.  Once you upload the site to the web server, you're going to get the root path of where it is on the file system of the server.

What you can do is make an old school activex control that the user can download from your site (they will be prompted before hand, there's no way around that) that can interact with the local computer, it's how Microsoft does it for WinXP's Windows/Microsoft Updates.  How you would go about doing this is beyond me as I've never made an activex browser control before.

----------


## jeztericp

Here's a toughy for ya.  my executable is in a folder on a network drive.  My R: drive is mapped to a folder a few levels above that folder.  when i use ANY of these methods I get this:
"R:\whatever\whateversub\myfolder\my.exe"
thats not what i want.  i want the actual path like this: 
"\\first\second\third\whatever\whateversub\myfolder\my.exe"

can anyone figure this one out for me?
please and thanks!

-JeZteR

----------


## JuggaloBrotha

When you map a network drive you get a path that has a local drive letter in your "My Computer" and when you use anything through that then that's the path you have, which is also the path your program has too.  What you can do is make a network shortcut to "\\first\second\third\whatever\whateversub\myfolder\my.exe" in your "Network Neighborhood" or the desktop (which works like a folder/file shortcut except it has the \\first part included in it) and the program will have/know the same path too.

----------


## jeztericp

so theres no GetFullPath or GetActualPath that i could pass a mapped drive or folder to?  that sux lol

ok thanks for the reply

-JeZteR

----------


## Kallog

> so theres no GetFullPath or GetActualPath that i could pass a mapped drive or folder to?  that sux lol
> 
> ok thanks for the reply
> 
> -JeZteR


A network path isn't really more "full" or "actual" than a local one. It's just different. Here's a code that I think finds the network location of a local drive letter. 

http://www.mvps.org/access/api/api0003.htm

So you'd find the local path, then convert the drive letter to the network path.

----------


## chris128

Here's a much simpler example that I wrote that gets the UNC path that a network drive maps to - it uses the same API as that example in the previous post but I think you will agree it is much more readable and .NET friendly  :Smilie:  http://cjwdev.wordpress.com/2009/12/...network-drive/

----------


## Kallog

Bloody jesus it is :P But I wonder why there isn't a .net function for that.

----------


## JuggaloBrotha

> Here's a much simpler example that I wrote that gets the UNC path that a network drive maps to - it uses the same API as that example in the previous post but I think you will agree it is much more readable and .NET friendly  http://cjwdev.wordpress.com/2009/12/...network-drive/


Now that, is neat.  I've wondered from time to time how windows knows a mapped drive vs a local drive, I've just never looked into it.

----------


## chris128

haha thanks  :Smilie:  hope its useful to someone

----------


## jeztericp

I was really hoping I wouldn't have to use the old stuff(api).  I really was hoping there was a .net way to do it.  I have found that they have "forgotten" to include several things in .net that you could do in vb6.

This will definitely work for now.  Thank you all very much.

-JeZteR

----------

