C# 将文件保存在我的项目中的指定文件夹中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14788217/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:59:42  来源:igfitidea点击:

Saving a file in a specified folder inside my project

c#file-io

提问by Arianule

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.

我正在创建一个 Xml 文件,我想将它保存在解决方案中我的项目内的指定文件夹中,我可以在解决方案资源管理器中访问它。

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

如何指定路径以便创建文件夹并将 xml 文件保存在其中?

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.?

抱歉,还是个新手……我错过了什么吗?

采纳答案by Jos Vinke

You can specify the path when you declare a new StreamWriter.

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

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

This comes down to:

这归结为:

  • ../ - Go up one directory
  • ../ - Go up one directory
  • Box.xml file here
  • ../ - 上一级目录
  • ../ - 上一级目录
  • Box.xml 文件在这里

So when you want the file created in a folder inside the root folder you could use:

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

  • "../foldername/Box.xml"
  • “../ FOLDERNAME/Box.xml”

But if you don't want to rely on your current file location you can also use:

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

AppDomain.CurrentDomain.BaseDirectory

That would make:

这将使:

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

Hope this helps.

希望这可以帮助。

回答by D J

Instead of using AppDomain.CurrentDomain.BaseDirectoryyou can just do it this way:

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

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

When you don't add anything, the basedirectory is automatically assumed.

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