C# 如何使用相对路径使用 StreamWriter 创建文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1198936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a file with StreamWriter using a relative path?
提问by Edward Tanguay
When I run the following code, an XML file is correctly createdin c:\temp
:
当我运行以下代码时,在 中正确创建了一个 XML 文件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-directoryunderneath 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 appearsin 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 在我的项目中创建一个具有相对路径的文件?
回答by Aamir
Does ./Data/CustomerMock2.xml
work?
不./Data/CustomerMock2.xml
工作?
using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))
回答by Henk Holterman
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.
但是,如果您在库中并且无权访问应用程序(或环境)对象,则应考虑创建 BaseFolder 参数或属性以让主应用程序控制文件夹。
回答by Chris S
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
您是否设置要在编译时复制的 XML 数据(因此它不在实际项目目录中,而是在 bin 文件夹中)?在这种情况下,您可以使用
string xmlFile = string.Format("{0}/Data/{1}",AppDomain.CurrentDomain.BaseDirectory,"myxml.xml");
回答by Thomas Levesque
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.
相对路径是相对于当前目录的。也许你不在 bin/debug 目录下......你应该基于 exe 目录构建绝对路径,如 Chris 所示。此外,StreamWriter 构造函数不会创建目录,如果它不存在,您需要显式创建它。