c# - 相对路径改变?

标签 c# .net path directory filestream

我有一个日志对象,它使用相对路径写入每日日志文件。这相当简单(.NET 4.0、VS 2010)。

public void LogLine(string txt)
{
    DateTime dt = DateTime.Now;
    if (CurrentDay != dt.Day)
    {
        string newFileName = "..\\Log\\" + programName + dt.Day + ".log";
        fs = new FileStream(newFileName, FileMode.Create, FileAccess.Write);
        sw = new StreamWriter(fs);
        CurrentDay = dt.Day;
    }
    sw.WriteLine(txt);
}

这几乎一直都很好用。但是,有时我会得到一个似乎是随机的 DirectoryNotFoundException,但路径完全不同。例如,当我第一次运行该程序时,它会创建一个文件:

C:\MyFiles\Log\MyApp19.log

在使用该程序并让它运行一整夜后,创建了一个新文件和流(在午夜后的第一个日志中),我回到 DirectoryNotFoundException 并声明如下内容:

C:\MyFiles\MyOtherFiles\Resources\Log\MyApp20.log

我唯一能想到的是:我在软件的整个生命周期中使用了几次 OpenFileDialog 和 SaveFileDialog,其中一个打开/保存对话框访问了一个文件

C:\MyFiles\MyOtherFiles\Resources\SavedFiles\

所以在我看来,当我使用对话框时,我打开/保存一些东西到 SavedFiles 目录中,当它创建新日志时,相对文件路径 ..\ 上升到 Resources(来自 SavedFiles),然后在 Resources 中找不到目录 Log并抛出异常。但是,我无法使用对话框重现问题,我认为相对路径是相对于可执行文件的?打开/保存文件对话框是否可以改变软件计算相对文件路径的方式?有人有什么想法吗?感谢您的宝贵时间!

最佳答案

我认为以下链接可以帮助您:

http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.aspx

注意以下部分:

Important: If the user of your application changes the folder in the FileDialog, then the current working directory for your application is set to the location specified in the FileDialog. To prevent this, set the RestoreDirectory property to true.

尝试使用 Microsoft 建议的路径方法,如上述链接中所述。

这也可以帮助你 http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx

问候

关于c# - 相对路径改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983567/

相关文章:

c# - 如何在没有 ASP.NET 模型验证的情况下根据需要在 Swagger 中标记属性?

c# - Monitor.Pulse 和 Monitor.Wait 之间的竞争条件?

ios - 如何修复 Xcode 路径错误

java - 从我的 jar 中复制文件非常简单

C# 检查数组中的值,转到现有值的位置

c# - 提高 SHA-1 ComputeHash 的性能

c# - Asp.Net 商店产品属性(尺寸、数量)

c# - 将多个 XSD 合并到一个文件中

.net - WPF/银光VS WinRT

macos - Mac OS X HFS+ 中最长的路径名字符串