创建一个Windows Application 接受其默认名称WindowsApplication1
若想获得WindowsApplication1的所在目录,可以用以下方法:
应用程序域:
AppDomain.CurrentDomain.BaseDirectory => E:/WindowsApplication1/WindowsApplication1/bin/Debug/
环境变量:
Environment.CurrentDirectory => E:/WindowsApplication1/WindowsApplication1/bin/Debug
用反射:
Reflection.Assembly.GetAssembly(GetType(WindowsApplication1.Form1)).CodeBase => file:///E:/WindowsApplication1/WindowsApplication1/bin/Debug/WindowsApplication1.EXE
但若自定义了一个类库Class1,公开了3个属性MyPath1,MyPath2,MyPath3,生成dll后被WindowsApplication1引用
Public Class Class1
shared ReadOnly Property MyPath1() As String
Get
Return AppDomain.CurrentDomain.BaseDirectory
End Get
End Property
shared ReadOnly Property MyPath2() As String
Get
Return Environment.CurrentDirectory
End Get
End Property
shared ReadOnly Property MyPath3() As String
Get
Return Reflection.Assembly.GetAssembly(GetType(Class1)).CodeBase
End Get
End Property
End Class
在WindowsApplication1中查询Class1的MyPath1,MyPath2和MyPath3.发现,MyPath1、MyPath2返回的并不是被 引用的Class1的特征,而是而只有MyPath3返回的才是Class1的文件位置。可见反射是多么强大的功能。
同样,反射也可以确定系统组件的路径:
获得TextBox的源程序集
Reflection.Assembly.GetAssembly(GetType(TextBox)).CodeBase => file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll