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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Arianule
  • 8,811
  • 45
  • 116
  • 174
  • What is shown in the solution explorer is what's included in your project, and doesn't necessarily show all files. If your developing for web you can try Server.MapPath to get to the desired directory. – reinder Feb 09 '13 at 12:41
  • Refer to this thread, it has multiple solutions, http://stackoverflow.com/questions/816566/how-do-you-get-the-current-project-directory-from-c-sharp-code-when-creating-a-c – Random IT Guy Feb 09 '13 at 12:44
  • What kind of solution use this xml file?(winform or WPF or Asp.net) – mas_oz2k1 Feb 09 '13 at 12:46
  • You need to manually include files in Sln Explorer iirc. – It'sNotALie. Feb 09 '13 at 12:58

2 Answers2

16

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.

Jos Vinke
  • 2,704
  • 3
  • 26
  • 45
1

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.

D J
  • 845
  • 1
  • 13
  • 27