using System.Reflection;
方法1:
Directory.GetCurrentDirectory()。
這個方法只能在.NET的完整版中使用,NETCF中不支持該功能,調用時會引發異常。
方法2:
System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)。
這個方法是MSDN中給出的針對NETCF平臺的,當在PC的NET完整版中獲取到的路徑中測試時,發現最終的路徑中帶有file:前綴,如file:\c:\debug,一般情況下我們並不需要這個前綴,可以手動將其去掉。
方法3:
System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName).
該方法也是針對NETCF給出的解決方案,當在PC的NET完整版測試中可以獲取到一致的結果。
PS:個人推薦使用方法3
----------------------------------------------
網上的一篇帖子介紹(未測試)
1: public class Configs
2: {
3: private string m_CurrentPath;
4: //取得作業平臺
5: private string Platform
6: {
7: get
8: {
9: return Environment.OSVersion.Platform.ToString();
10: }
11: }
12:
13: public string CurrentPath
14: {
15: get
16: {
17: if (Platform.Equals("WinCE"))
18: {
19: m_CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
20: }
21: else if (Platform.Equals("Win32NT"))
22: {
23: m_CurrentPath = Directory.GetCurrentDirectory();
24: }
25:
26: return m_CurrentPath;
27: }
28: }
29:
30: public Configs()
31: {
32:
33: }
34: }
1: //實作
2: public Form1()
3: {
4: InitializeComponent();
5:
6: Configs config = new Configs();
7: MessageBox.Show(config.CurrentPath);
8: }