Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a file in a specified folder inside my project

Tags:

c#

file-io

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

like image 559
Arianule Avatar asked Feb 09 '13 12:02

Arianule


People also ask

What is the purpose of saving your document to a specific folder?

Saving a file is critical for editing, preserving, and sharing your work. If the program closes or your computer shuts down unexpectedly while you are using Word, don't worry. By default, Word automatically saves your work every 10 minutes and will reload that save upon reopening the program.


2 Answers

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

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

This comes down to:

  • ../ - Go up one directory
  • ../ - Go up one directory
  • Box.xml file here

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

  • "../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.

like image 126
Jos Vinke Avatar answered Oct 28 '22 18:10

Jos Vinke


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

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

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

like image 35
D J Avatar answered Oct 28 '22 18:10

D J