./ 当我使用 OpenFileDialog 时更改目标
我使用流写入器来记录错误,
其设计方式(请不要问为什么)是每次应用程序必须记录消息时打开一个新的流写入器。 它将所有内容输出到 ./Logs/[current-date].txt,通常解析为“c:\myappfolder\logs[current-date].txt”
一切正常,但在我使用打开文件对话框后说:“ C:\home\myfolder\myfile" 流写入器尝试写入 "c:\home\myfolder\logs[current-date].txt"
我知道这个问题的解决方案,但我只是不明白发生了什么
I'm using a streamwriter to log errors
the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt"
Everything works correctly, but after I use an open file dialog to say, "C:\home\myfolder\myfile" the streamwriter tries to write to "c:\home\myfolder\logs[current-date].txt"
I know solutions to this problem but i just dont understand what's going on
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当前目录是进程范围的值。
OpenFileDialog
正在更改当前目录。如果您使用 .NET
OpenFileDialog
类,则可以将RestoreDirectory
属性设置为true
以告诉对话框保留当前目录(尽管RestoreDirectory
的文档编写方式可能存在一些线程问题,我想这可能会使这仍然不适合日志记录工具)。The current directory is a process wide value.
The
OpenFileDialog
is changing the current directory.If you're using the .NET
OpenFileDialog
class, you can set theRestoreDirectory
property totrue
to tell the dialog to leave the current directory alone (although the way the docs forRestoreDirectory
is written there may be some threading issues, which I imagine might make this still inappropriate for a logging facility).正如 Mike B 所说,
OpenFileDialog
可能会更改当前目录。 由于./
是相对于当前的,所以它也会改变。RestoreDirectory
属性修改此行为。而是做这样的事情:
取自 MSDN。
As Mike B said,
OpenFileDialog
may change current directory. Since./
is relative to current, that changes too.The
RestoreDirectory
property modifies this behavior.Do something like this rather:
Taken from MSDN.
Mike B 绝对正确。
如果您使用本机 API 而不是 .NET,则需要在 OPENFILENAME 结构中设置 OFN_NOCHANGEDIR 选项。 文档指出它不适用于 Windows XP,但不确定这是否适用于 .NET 版本。
无论您如何解决此问题,请注意,每次打开文件对话框时,它都会在原始文件夹中打开。 如果您打开大量文件,治疗方法可能比疾病本身更糟糕。 您最好在程序启动时获取当前目录,并将其添加到您的文件名中。
Mike B is absolutely correct.
If you're using the native API rather than .NET, you need to set the OFN_NOCHANGEDIR option in the OPENFILENAME structure. The documentation states that it doesn't work for Windows XP though, not sure if this applies to the .NET version or not.
No matter how you fix this, be aware that every time the file dialog opens it will open back in your original folder. If you open lots of files, the cure may be worse than the disease. You may be better off getting the current directory when the program starts, and prepending it to your filenames.