domingo, 13 de octubre de 2013

Obtener la ruta de ejecución en .Net


Buscando un poco en internet encontré varias formas de saber la ruta de donde se está ejecutando nuestra aplicación (Windows Forms). Al final me quede con Application.StartupPath por qué es lo que necesitaba hoy, pero hay que tener en cuenta varias cosas.

 

Estas páginas fueron de gran ayuda:

http://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-net-in-a-console-app

http://stackoverflow.com/questions/1460684/how-to-get-file-name-of-exe

 

Por ejemplo System.Reflection.Assembly.GetExecutingAssembly().Location no siempre puede dar la misma ruta, puede ser que este corriendo en un directorio temporal. En uno de los comentarios de la bibliografía que agrego dice que ejecutado desde una aplicación web en IIS el resultado sería algo así C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\e9a4e8db_5d84cc01. Para obtener la ruta donde normalmente reside en disco o el directorio de instalación tendríamos que usar System.Reflection.Assembly.GetExecutingAssembly().CodeBase

 

Sin más enredos pongo los ejemplos. Usar el más conveniente para cada situación.

 

' to get the location the assembly is executing from

' (not neccesarily where the it normally resides on disk)

' in the case of the using shadow copies, for instance in NUnit tests,

' this will be in a temp directory.

Dim path As String = System.Reflection.Assembly.GetExecutingAssembly().Location

' once you have the path you get the directory with:

Dim directory = System.IO.Path.GetDirectoryName(path)

 

 

' To get the location the assembly normally resides on disk or the install directory

Dim path As String = System.Reflection.Assembly.GetExecutingAssembly().CodeBase

Dim directory = System.IO.Path.GetDirectoryName(path)

 

 

Dim path As String = Application.ExecutablePath

Dim directory = System.IO.Path.GetDirectoryName(path)

 

 

Dim path As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

Dim directory = System.IO.Path.GetDirectoryName(path)

 

 

Dim directory = Application.StartupPath