6

I am creating an Xml file and I want to save it in a specified folder inside my project within the solution where I can access it in the Solution Explorer.

How can I specify the path so that a folder is created and the xml file saved inside it?

As it is at the moment it creates the file in the root directory of my project and I cannot view it in Solution Explorer.

 XmlSerializer serializer = new XmlSerializer(typeof(BoxSet));
 TextWriter textWriter = new StreamWriter("../../Box.xml");

Sorry, still a newbie...am I missing something.?

4

2 回答 2

15

您可以在声明新的 StreamWriter 时指定路径。

TextWriter textWriter = new StreamWriter("../../Box.xml");

这归结为:

  • ../ - 上一个目录
  • ../ - 上一个目录
  • Box.xml 文件在这里

因此,当您希望在根文件夹内的文件夹中创建文件时,您可以使用:

  • “../文件夹名称/Box.xml

但是,如果您不想依赖当前文件位置,也可以使用:

AppDomain.CurrentDomain.BaseDirectory

这将使:

var path = String.Format("{0}foldername\Box.xml", AppDomain.CurrentDomain.BaseDirectory);
TextWriter textWriter = new StreamWriter(path);

希望这可以帮助。

于 2013-02-09T12:56:10.903 回答
1

而不是使用AppDomain.CurrentDomain.BaseDirectory你可以这样做:

    TextWriter textWriter = new StreamWriter("foldername\\Box.xml");

当您不添加任何内容时,将自动假定基本目录。

于 2020-03-31T15:11:32.157 回答