如何使用相对路径使用 StreamWriter 创建文件?
当我运行以下代码时,在 c:\temp
中正确创建了 XML 文件:
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Models.Customer>));
using (StreamWriter wr = new StreamWriter("C:/temp/CustomerMock2.xml"))
{
xs.Serialize(wr, CustomerList);
}
但是,我实际上希望在项目下的一个子目录,但是当我这样做时:
using (StreamWriter wr = new StreamWriter("Data/CustomerMock2.xml"))
它只是表现得好像它写入了它,但文件永远不会出现在该目录中:
C: \Projects\Prototype12\CustomersModul\bin\Debug\Data
。
如何使用 StreamWriter 在项目内创建具有相对路径的文件?
When I run the following code, an XML file is correctly created in c:\temp
:
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Models.Customer>));
using (StreamWriter wr = new StreamWriter("C:/temp/CustomerMock2.xml"))
{
xs.Serialize(wr, CustomerList);
}
However, I actually want it to be created in a sub-directory underneath the project, but when I do this:
using (StreamWriter wr = new StreamWriter("Data/CustomerMock2.xml"))
it just acts as if it writes it but the file never appears in that directory:
C:\Projects\Prototype12\CustomersModul\bin\Debug\Data
.
How can I create a file with StreamWriter with a relative path inside my project?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
依赖“当前目录”概念总是很危险的,因此您需要一个起点。 在WinForms项目中,您可以获取.EXE的位置,
在WPF中会有类似的东西。
但是,如果您位于库中并且无权访问应用程序(或环境)对象,则应考虑创建 BaseFolder 参数或属性,以让主应用程序控制文件夹。
It is always dangerous to rely on the 'Current Directory' concept, so you will need a starting point. In a WinForms project, you can get the location of the .EXE with
In WPF there will be something similar.
But if you are in a library and do not have access to the Application (or Environment) objects, you should consider making a BaseFolder parameter or property to let the main application take control over folders.
./Data/CustomerMock2.xml
有效吗?Does
./Data/CustomerMock2.xml
work?您是否设置要在编译时复制的 XML 数据(因此它不在实际的项目目录中,而是在 bin 文件夹中)? 在这种情况下,您可以使用
Are you setting the XML data to be copied at compile time (so it's not in the actual project directory, but the bin folder)? In which case you can get to it using
相对路径是相对于当前目录的。 也许你不在 bin/debug 目录中...你应该根据 exe 目录构建绝对路径,如 Chris 所示。
此外,StreamWriter 构造函数不会创建该目录,如果该目录不存在,则需要显式创建它。
Relative paths are relative to the current directory. Maybe you're not in the bin/debug directory... You should build the absolute path based on the exe directory, as shown by Chris.
Also, the StreamWriter constructor won't create the directory, you need to create it explicitly if it doesn't exist.