Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read from a file referenced within a solution?

Status
Not open for further replies.

DMFW62

Programmer
Aug 10, 2008
2
GB
I'm sure this is a pretty basic question with an easy answer but I'm a C# beginner and I'm struggling with it...

I've added an XML fragment to my solution and I've noticed that the file is copied into the bin/debug folder and gets copied into bin/release when I do a build. I have the "Copy To Output Directory" property set to Copy Always.

How can I actually read from this file in code using a path that will work in debug mode and when the assembly is shipped?

I need to do something like:-

Code:
string sXMLFragmentTemplate = System.IO.File.ReadAllText(@"MyXMLFileFragment.xml");

where "MyXMLFileFragment.xml" is the file I have added to the solution but I don't know how to specify a path so that it will be picked up from the solution in debug and when built. Can anyone help me?
 
I have found an answer to this problem with the following code:-

Code:
string sXMLFragmentPath = System.Windows.Forms.Application.StartupPath;
string sXMLFragmentTemplate = System.IO.File.ReadAllText(sXMLFragmentPath + @"\MyXMLFragment.xml");

and I've also found that you can use this property:-

Code:
System.Reflection.Assembly.GetExecutingAssembly().Location

although the value returned includes the name of the project exe which would have to be stripped off for my purposes. I'm not sure I fully understand the difference between these two ways of obtaining the path and the merits or demerits of either method. I've also found that there is an interesting property called UserAppDataPath on the System.Windows.Forms.Application object which refers to a path in the "My Documents" folder, but this looks like it is intended to serve a different purpose.

If anyone can enlighten me about the significance of these various paths that would be helpful but to me it looks like System.Windows.Forms.Application.StartupPath is the one I should be going for...

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top