-3

My application intends to export an xml file, and I am aware of that, the XML file is stored in the bin folder.
The code which handles the xml file path is having an issue at the moment. The code is stored in the MainForm.cs.

enter image description here

As you can see, the the xml file is located in the blue circle and MainForm.cs is located in the red circle. The full path of the xml file is:

var testFileFullPath = @"C:\Users\Daniel\Desktop\Assignment\WoodStock\WoodStock\bin\Debug\output.xml";

I wrote a if-statement to check if the file exist, as followed:

var existing =  (File.Exists(testFileFullPath)) ? "Success" : "Fail";

VS log the result as Success. However, if I use the relative path as follow:

 var testFileRelativePath = @"bin\Debug\output.xml";

and run the if-statement:

var existing =  (File.Exists(testFileRelativePath)) ? "Success" : "Fail";

VS log the result as Fail. My current working directory (MainForm.cs) is var currentWorkingPath = @"C:\Users\Daniel\Desktop\Assignment\WoodStock\WoodStock\MainForm.cs";

I am not sure if this is a VS bug or any restriction? Any solution? Thanks in advance.

Nan
  • 496
  • 3
  • 21
  • What is the [working directory](https://stackoverflow.com/a/21726439/1043380) path when you execute the line? Is it the path to your bin/Debug directory? – gunr2171 Feb 22 '21 at 03:20
  • var currentWorkingPath = @"C:\Users\Daniel\Desktop\Assignment\WoodStock\WoodStock\MainForm.cs"; – Nan Feb 22 '21 at 03:29
  • The Current Working Directory is always a _directory_, it can never be a file. If we ignore the file from that string, then your Current Working Directory is the project directory, which explains why your code can't see the xml file. If that path is indeed correct, try moving the xml file to the same folder with the form. – gunr2171 Feb 22 '21 at 03:31
  • I am aware of that. I am really confused that the project can recognise the full path, not the relative path. Is it because the bin folder is restricted when the project is compiling ? – Nan Feb 22 '21 at 03:35
  • You should not use relative paths like that since you can't be sure what the working directly is. You need to be relative to where your file is, not relative to the working directory (that can change). I'd suggest Googling for `c# get path relative to executing assembly` and `Path.Combine`. – mjwills Feb 22 '21 at 03:45

1 Answers1

1

Your relative path in relation to your compiled application is in the same folder.

Notice the WoodStock.exe (your complied exe) and your output.xml in your bin/Debug folder which is the same folder.

So your relative path should be like this:

 var testFileRelativePath = @"output.xml";
Markuzy
  • 483
  • 6
  • 10