0

We have a C# backend application here at work that I've written. It saves it's state to a txt file so that when it starts up again it'll have the details it needs to continue working. If I add a key to the registry to start the app when the user signs on (HKCU) then the app will start but it fails to read it's state txt file.

I don't know what's happening here. The txt file has to be in the same folder as the app and I load it like this:

String savepath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), SaveFile);
if (File.Exists(savepath)) LoadState();

And I actually read the file using:

String[] lines = File.ReadAllLines(SaveFile);

None of this is really complicated but because the contents of the txt file aren't being loaded, I am assuming that either 1) the File.Exists() is coming back false or 2) it's coming back true and File.ReadAllLines() is coming back empty.

If I close the program and immediately re-run it then it reads the file just fine. What can I do to have my app read it's file when the computer starts up?

4

3 回答 3

2

实际上,如果当前目录与 不同,则您没有检查也没有打开同一个文件(您传递的是绝对路径File.Exists和相对路径),当您在启动时启动程序时就是这种情况(我想应该是,但我不确定 - 但是,它绝对不是您的应用程序文件夹)。File.ReadAllLinesPath.GetDirectoryName(Application.ExecutablePath)%WINDIR%\System32

String savepath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), SaveFile);
if (File.Exists(savepath)) LoadState();
    String[] lines = File.ReadAllLines(SaveFile);

应该

String savepath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), SaveFile);
if (File.Exists(savepath)) LoadState();
    String[] lines = File.ReadAllLines(savepath);

它会第一次失败,因为当你手动启动它和 Windows 在启动时启动它时工作目录会有所不同。

于 2013-09-12T20:05:22.250 回答
0

您应该确保当您执行您的应用程序时,它具有与系统执行它时相同的权限,否则它将无法访问该文件。

此外,您可能想检查文件是否因某种原因被锁定,并且可以检查此线程:如何检查文件锁定?

于 2013-09-12T20:18:25.310 回答
0

尝试删除File.Exists()检查(暂时),看看它是否会返回更详细的消息。它将有助于具体诊断失败的原因。该文件有可能根本不存在——在这种情况下,您应该记录它正在寻找的完整路径,因为它可能不是您所期望的。如果进程以不同的身份启动,也可能存在权限问题。

于 2013-09-12T20:06:53.737 回答