3

I would like to check file exists in the same folder where is my program. If is do something. How i can fix that ?

private void button12_Click(object sender, EventArgs e)
{

    if (File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + "tres.xml"))
         Upload("tres.xml");

}
Jim
  • 2,974
  • 2
  • 19
  • 29
Ops
  • 115
  • 2
  • 9
  • 2
    Possible duplicate of [How to detect if a file exist in a project folder?](http://stackoverflow.com/questions/3446915/how-to-detect-if-a-file-exist-in-a-project-folder) – Jim Dec 09 '16 at 10:08
  • 2
    Use `Path.Combine` instead of concatenating the path – ColinM Dec 09 '16 at 10:10

2 Answers2

7

The reason why your code doesn't work is that GetDirectoryName returns no \ at the end. That's even documented:

The string returned by this method consists of all characters in the path up to but not including the last DirectorySeparatorChar or AltDirectorySeparatorChar

Use Path.Combine to get the correct directory separator char:

string path =  Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "tres.xml");
if(File.Exists(path))
{
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

You can just simply use:

File.Exists("tres.xml");

This checks the current directory of your .exe

ThePerplexedOne
  • 2,920
  • 15
  • 30
  • 1
    Note that it is the _current directory of your .exe_, that means `bin\Debug` (if you run from VS) and not your project root. – BrunoLM Dec 09 '16 at 10:12