StreamReader 在 C# 中的错误目录中查找文件
我有一个使用 Windows 窗体的程序,在该窗体中我使用 openFileDialog 在某个目录中打开文件。然后我在不同的函数中使用 StreamReader,并且我的 big/debug 目录中有第二个文件,我希望 StreamReader 打开该文件。但由于某种原因,在我使用 openFileDialog 打开第一个文件后,StreamReader 会像往常一样在该目录中查找第二个文件,而不是在 bin/debug 中。
有谁知道他为什么这样做以及我该如何解决它?
提前致谢,
格雷格
I have a program where I am using windows form, in that form I use openFileDialog where I open a file in some directory. Then I use in a different function a StreamReader and I have a 2nd file in my big/debug directory which I want the streamReader to open. But for some reason after I open the 1st file with the openFileDialog the StreamReader looks for the 2nd file in that directory instead in bin/debug as usual.
Does anyone know why he does that and how can I solve it?
Thanks in advance,
Greg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
OpenFileDialog
具有这种行为;它更改应用程序的当前目录。为了防止这种情况发生,您可以使用OpenFileDialog
的RestoreDirectory
属性。The
OpenFileDialog
has that behavior; it alters the current directory for the application. To prevent this from happening, you can use theRestoreDirectory
property of theOpenFileDialog
.当您在打开的文件对话框中更改目录时,这也会导致应用程序的工作目录发生更改。因此,如果您尝试使用相对路径,它将查找到错误的位置。
解决方案是RestoreDirectory。
When you change directory in an open file dialog, this also causes your application's working directory to change. So if you are trying to use relative paths, it will look in the wrong place.
The solution is RestoreDirectory.
如果不指定完整的文件路径而仅指定文件名,则表示该文件位于当前目录中。当您使用 OpenFileDialog 时,它会更改当前目录。
如果您想要访问某处的文件,无论当前目录设置为何,您都必须为其指定完整路径。您可以使用
Application.StartupPath
获取程序所在文件夹的路径。If you don't specify a complete file path but only a file name, that means that the file is in the current directory. When you use the OpenFileDialog, it changes the current directory.
If you want to access a file somewhere regardless of what the current directory is set to, you have to specify a complete path for it. You can use
Application.StartupPath
to get the path to the folder where your program is.