xml file as part of c# program

  • Thread starter Thread starter Jason Gleason
  • Start date Start date
J

Jason Gleason

I'm currently using visual studio.net to develop a c# windows application. I
was wondering if there is any way to make an xml file (with say
connectionstring data in it) part of the program. Like when I compiled the
program i could reference the file somehow without having it actually be in
the debug directory, or actually having to add it to export to setup
projects (and making connection string viewable to anyone using it).

I'm probably not explaining what I mean to well, but i can answer further
questions if anyone has any.
 
I'm currently using visual studio.net to develop a c# windows
application. I was wondering if there is any way to make an xml file
(with say connectionstring data in it) part of the program. Like when
I compiled the program i could reference the file somehow without
having it actually be in the debug directory, or actually having to
add it to export to setup projects (and making connection string
viewable to anyone using it).

I know exactly what you mean - I've run into the same problem. My solution
was pretty low-brow but it works - just look for the file in the current
directory first, then the parent directory, then the parent's parent
directory. In VS.net, the third location will find your file and will do
whatever it needs to do. When you deploy the program, the first location
will find the file.

Something like this:

string fname = "config.xml";
if (!File.Exists(fname))
{
if (File.Exists(@"..\" + fname)) fname = @"..\" + fname;
else if (File.Exists(@"..\..\" + fname)) fname = @"..\..\fname";
else MessageBox.Show("Couldn't find config file.");
}

-mdb
 
Jason,

If I understand you correct, you want to include the XML file into the
application file and use it at runtime from your application. If this is the
case then what you should do is to add the file to your project, select it
and change it's "Build Action" to "Embedded resource" in the property
grid.

Then when you need to use it, you should do like this

using System.IO;
using System.Xml;

Stream xmlStream =

this.GetType().Assembly.GetManifestResourceStream("Fullnamespace.Name.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlStream);

Now you have an XML document you can read from.

Hope this helps,

//Andreas
 
Back
Top