2009-07-09 96 views
6

我如何知道這是一個應用程序的當前文件夾? 我的意思是...有沒有辦法知道exe文件位於運行代碼的哪個位置?Compact Framework當前文件夾

在此先感謝

回答

6
string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase; 
string fullAppPath = Path.GetDirectoryName(fullAppName); 
8

的Windows Mobile不具有當前文件夾的概念。無論您的應用程序位於何處,「當前文件夾」基本上始終設置爲文件系統的根目錄。

爲了讓您的應用程序所在的路徑,你可以使用Assembly.GetExecutingAssembly(),並CodeBase屬性或方法GetName()

4

不要打製。

Microsoft不希望您將程序文件文件夾用於其他任何裝配。應用程序數據,保存文件等用戶需要知道的有關在我的文檔中進入的配置文件應該存在。

賈爾夫的答案將工作,但你正在與系統作鬥爭。除非他們是一個非常好的理由,爲什麼你想知道你的程序集是在什麼文件夾,那麼我會建議反對它。

2

您可以使用GetModuleFileName

在下面的示例,GetExecutablePath返回exe文件的位置,並GetStartupPath返回exe文件的目錄中的方法。

using System; 
using System.ComponentModel; 
using System.IO; 
using System.Runtime.InteropServices; 
using System.Text; 

class Program 
{ 
    [DllImport("coredll", SetLastError = true)] 
    public static extern uint GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, [MarshalAs(UnmanagedType.U4)] int nSize); 

    [DllImport("coredll")] 
    public static extern uint FormatMessage([MarshalAs(UnmanagedType.U4)] FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, out IntPtr lpBuffer, uint nSize, IntPtr Arguments); 

    [DllImport("coredll")] 
    public static extern IntPtr LocalFree(IntPtr hMem); 

    [Flags] 
    internal enum FormatMessageFlags : uint 
    { 
     AllocateBuffer = 256, 
     FromSystem = 4096, 
     IgnoreInserts = 512 
    } 

    public static string GetModuleFileName(IntPtr hModule) 
    { 
     StringBuilder lpFilename = new StringBuilder(short.MaxValue); 
     uint num = GetModuleFileName(hModule, lpFilename, lpFilename.Capacity); 
     if (num == 0) 
     { 
      throw CreateWin32Exception(Marshal.GetLastWin32Error()); 
     } 
     return lpFilename.ToString(); 
    } 

    private static Win32Exception CreateWin32Exception(int error) 
    { 
     IntPtr buffer = IntPtr.Zero; 
     try 
     { 
      if (FormatMessage(FormatMessageFlags.IgnoreInserts | FormatMessageFlags.FromSystem | FormatMessageFlags.AllocateBuffer, IntPtr.Zero, (uint)error, 0, out buffer, 0, IntPtr.Zero) == 0) 
      { 
       return new Win32Exception(); 
      } 
      return new Win32Exception(error, Marshal.PtrToStringUni(buffer)); 
     } 
     finally 
     { 
      if (buffer != IntPtr.Zero) 
      { 
       LocalFree(buffer); 
      } 
     } 
    } 

    public static string GetStartupPath() 
    { 
     return Path.GetDirectoryName(GetExecutablePath()); 
    } 

    public static string GetExecutablePath() 
    { 
     return GetModuleFileName(IntPtr.Zero); 
    } 
} 
+0

對於這樣一個小釘子,這是一個非常大的錘子。 – ctacke 2009-07-10 22:17:33

2

下面是正確的。

string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase; 
fullAppPath = Path.GetDirectoryName(fullAppName);
對於其他語言的其他語言的版本其他語言的其他語言版本 link