Correct File Path within C# Console Application

J86 picture J86 · Apr 6, 2013 · Viewed 52k times · Source

Can someone please tell me how I can get the correct file path for the file data.xml? Here is where the file sits:

enter image description here

Here is my C# code that is checking to see if the file exists for the supplied path:

public class Parser
{
    static void Main(string[] args)
    {
        Console.WriteLine(File.Exists("App_Data/data.xml"));
        Console.Read();
    }
}

I keep getting False, meaning such a file does not exist. So file paths I've tried so far include:

"~/App_Data/data.xml"
"/App_Data/data.xml"
"App_Data/data.xml"

If this was a Web application, I would know what to do, by using the HttpContext and getting at the file. But since this is a Console application, I don't know.

On a related note, what is the difference between a Console application and an Executable application? Am I correct that there is no difference, since a Console App can be an Executable app if it has a Main method?

Thanks

Answer

Leon picture Leon · Apr 6, 2013

You can also add data.xml to your output build directory. You will need to right click on the file and select Copy if newer or Copy always for the Copy to output directory option.

Then you can use the following:

Console.WriteLine(File.Exists("App_Data/data.xml")); // Should print True

However, if you expect data.xml to change then just point to the full path, somewhere outside your project (assuming App_Data/data.xml is copied to C:/Temp) then:

Console.WriteLine(File.Exists("C:/Temp/App_Data/data.xml")); // Prints True

Also, for your other question related to a console and an executable application, the exe can be a different application type such as console or wpf or winforms (that's the way visual studio groups these).