2

我需要检查与可执行文件位于同一目录中的文件。

目前我正在使用这段代码 -

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();
    }

两者都在做同样的工作,但我不确定哪一个更强大。我想不出任何一种情况都会失败,但同时我对这两种方法都有一种可疑的感觉。

哪个更健壮,或者对于这个简单的问题还有其他更好的选择吗?

4

3 回答 3

3

第一个使用当前目录(可以通过 Directory.SetCurrentDirectory(dir) 设置),因此第二种方法比第一种方法更健壮。

于 2013-10-11T10:15:58.707 回答
3

他们所做的工作并不完全相同:第一个将查找相对于当前工作目录的文件,这可能与第二个不同。

两者都不是完全健壮的,因为GetEntryAssembly如果托管程序集已从非托管应用程序加载,并且Assembly.Location可能是程序集 Dowmload 缓存,则可以返回 null。

最好的解决方案是使用AppDomain.CurrentDomain.BaseDirectory.

于 2013-10-11T10:27:50.340 回答
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;
    }
}
于 2013-10-11T10:37:17.063 回答