5

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?

4

4 回答 4

9

依赖“当前目录”概念总是很危险的,因此您需要一个起点。在 WinForms 项目中,您可以使用以下命令获取 .EXE 的位置

string exeFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

在 WPF 中会有类似的东西。

但是,如果您在库中并且无权访问应用程序(或环境)对象,则应考虑创建 BaseFolder 参数或属性以让主应用程序控制文件夹。

于 2009-07-29T09:10:18.883 回答
5

./Data/CustomerMock2.xml行得通吗?

using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))
于 2009-07-29T09:08:42.163 回答
4

您是否在编译时设置要复制的 XML 数据(所以它不在实际的项目目录中,而是在 bin 文件夹中)?在这种情况下,您可以使用

string xmlFile = string.Format("{0}/Data/{1}",AppDomain.CurrentDomain.BaseDirectory,"myxml.xml");
于 2009-07-29T09:16:28.560 回答
0

相对路径是相对于当前目录的。可能你不在 bin/debug 目录下……你应该根据 exe 目录构建绝对路径,如 Chris 所示。此外,StreamWriter 构造函数不会创建目录,如果它不存在,您需要显式创建它。

于 2009-07-29T09:22:13.183 回答