2013-10-11 35 views
2

我需要檢查與可執行文件在同一目錄中的文件。File.Exists()是否總是在與可執行文件相同的目錄中搜索?

目前我使用此代碼 -

if (!File.Exists(versionFile)) 
{ 
    File.Create(versionFile).Close();   
} 

而且在一個地方我用這:

string file =  
    Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) 
     + "\\" + args.Executable; 
    if (File.Exists(file)) { 
     Process.Start(file); 
     Application.Exit(); 
    } 

兩者都做同樣的工作,但我不知道哪一個更堅固。我想不出任何一方都會失敗的情況,但同時我對這兩種方法都有一種腥意。

哪一個更強大或有其他更好的替代這個簡單的問題?

+1

爲什麼不使用'Path.Combine(Application.StartupPath,versionFile);'? –

+0

是的,但Application.StartupPath在類庫/控制檯應用程序中不可用。它需要System.Windows.Forms的引用 –

+0

'winforms'標籤欺騙了我。 –

回答

3

他們沒有完成相同的工作:第一個將查找與當前工作目錄相關的文件,該文件可能與第二個工作目錄不同。

既不是完全健壯的,因爲GetEntryAssembly可以返回null,如果託管程序集已從非託管應用程序加載,並且Assembly.Location可能是大會Dowmload緩存。

The best solution is to use AppDomain.CurrentDomain.BaseDirectory

+0

嗯有趣! thx –

3

第一個使用當前目錄(可以通過Directory.SetCurrentDirectory(dir)設置),所以第二個方法比第一個方法更強大。

+1

即使程序不改變當前目錄,當前目錄也不一定是可執行文件的目錄。 – hvd

+0

當前目錄也可以通過設置'Environment.CurrentDirectory'屬性,'Environment.CurrentDirectory = dir;'來改變。這似乎是等同的。 –

1

我用:

string startupPath = null; 

using (var process = Process.GetCurrentProcess()) 
{ 
    startupPath = Path.GetDirectoryName(process.MainModule.FileName); 
} 

的原因是這是唯一一個我發現可靠直到現在。作爲一個側面說明了Application.StartupPath做到這一點:

public static string StartupPath 
{ 
    get 
    { 
     if (Application.startupPath == null) 
     { 
      StringBuilder buffer = 
       new StringBuilder(260); 
      UnsafeNativeMethods.GetModuleFileName(
       NativeMethods.NullHandleRef, buffer, buffer.Capacity); 
      Application.startupPath = 
       Path.GetDirectoryName(((object)buffer).ToString()); 
     } 
     new FileIOPermission(
      FileIOPermissionAccess.PathDiscovery, 
      Application.startupPath).Demand(); 
     return Application.startupPath; 
    } 
} 
+0

怎麼樣AppDomain.CurrentDomain.BaseDirectory –

+0

在某些情況下,咬了我,像dinamically加載程序集。 –

+0

如果您沒有完全信任,則「process.MainModule.FileName」可能無法訪問。另外它在ASP.NET應用程序或VSTO插件中可能不太有用。因此AppDomain.CurrentDomain.BaseDirectory可能是最好的。 – Joe

相關問題