Friday, October 15, 2010

Reference files via relative path in C# using Visual Studio 2010

While building solutions in Visual Studio especially writing console applications, we come across a situation where we need to refer other files in our code. Reading and writing in XML files are the most common example of such actions. And obviously we do not want to set absolute path in our code for these files. So how we can do this in Visual Studio 2010. For example, in my C# code, I am referring a XML file “UserProfileProperties.xml” which is placed on the same level where “Program.cs” is located.


When I run this code, it gives me FileNotFoundException.


To solve this issue, I select this xml file and change value of “Copy to Output Directory” from Do not copy to Copy always. After this change, above C# code starts working.


No comments:

Post a Comment