简体   繁体   English

如何使用相对路径使用StreamWriter创建文件?

[英]How can I create a file with StreamWriter using a relative path?

When I run the following code, an XML file is correctly created in c:\\temp : 当我运行以下代码时,在c:\\temp 正确创建了一个XML文件:

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 . C:\\Projects\\Prototype12\\CustomersModul\\bin\\Debug\\Data

How can I create a file with StreamWriter with a relative path inside my project? 如何使用StreamWriter创建一个带有项目内相对路径的文件?

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 在WinForms项目中,您可以获取.EXE的位置

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

In WPF there will be something similar. 在WPF中会有类似的东西。

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. 但是如果您在库中并且无法访问Application(或Environment)对象,则应考虑使用BaseFolder参数或属性让主应用程序控制文件夹。

./Data/CustomerMock2.xml有效吗?

using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))

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)? 您是否在编译时设置要复制的XML数据(因此它不在实际的项目目录中,而是在bin文件夹中)? In which case you can get to it using 在这种情况下,您可以使用它

string xmlFile = string.Format("{0}/Data/{1}",AppDomain.CurrentDomain.BaseDirectory,"myxml.xml");

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. 也许你不在bin / debug目录中...你应该根据exe目录构建绝对路径,如Chris所示。 Also, the StreamWriter constructor won't create the directory, you need to create it explicitly if it doesn't exist. 此外,StreamWriter构造函数不会创建目录,如果它不存在,您需要显式创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM