什么会导致一个执行应用程序的当前目录改变? [英] What would cause the current directory of an executing app to change?

查看:113
本文介绍了什么会导致一个执行应用程序的当前目录改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#应用程序,包括以下code:

I have a C# application that includes the following code:

string file = "relativePath.txt";

//Time elapses...

string contents = File.ReadAllText(file);

这工作得很好,大部分时间。该文件被读取相对于该应用程序被启动的目录。然而,在测试中,我们发现,如果单独留在家中约5小时,应用程序将抛出一个 FileNotFoundException异常说C:\ Documents和Settings \管理员联系\ relativePath .TXT无法被发现。如果读取文件的动作是立即运行不过,该文件从正确的位置,我们称之为改为C:\富\ relativePath.txt

This works fine, most of the time. The file is read relative to the directory that the app was started from. However, in testing, it has been found that if left alone for about 5 hours, the app will throw a FileNotFoundException saying that "C:\Documents and Settings\Adminstrator\relativePath.txt" could not be found. If the action that reads the file is run right away though, the file is read from the proper location, which we'll call "C:\foo\relativePath.txt"

怎么办?而且,什么是最好的解决?解决对 Assembly.GetEntryAssembly()。位置

What gives? And, what is the best fix? Resolving the file against Assembly.GetEntryAssembly().Location?

推荐答案

如果该文件始终是相对路径可执行程序集一中,那么是的,使用Assembly.Location。我一直都用Assembly.GetExecutingAssembly如果适用,虽然不是Assembly.GetEntryAssembly。这意味着,如果你从一个DLL访问文件,路径将是相对于DLL的路径。

If the file is always in a path relative to the executable assembly, then yes, use Assembly.Location. I mostly use Assembly.GetExecutingAssembly if applicable though instead of Assembly.GetEntryAssembly. This means that if you're accessing the file from a DLL, the path will be relative to the DLL path.

这篇关于什么会导致一个执行应用程序的当前目录改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆