Nan
Nan

Reputation: 524

Relative file path issue in Visual Studio

I am working on one of my assignment for C# programming language. My application needs to read a file from a location; and the file is a .csv file. I am using relative file path in this assignment, as the tutor need to run the application on his pc and the resource file needs to be disclosed in the folder; otherwise, absolute file path is much easier.

The code needs to read the file is in MainForm.cs and the csv file name is stocklist.csv. I put the csv file into the same directory as the MainForm.cs . As you can see in the image, i have marked them in the red circle.

enter image description here

In MainForm.cs file, I tried to store the csv file's path in a string object and use it later on.

string CSV_FilePath = "./stocklist.csv";

But we i run my code, Visual Studio throw an error saying, the file can not be located. I have read the document regarding relative file path and absolute file path. I still can not figure out why the code is running into an error. Thanks in advance.

Upvotes: 0

Views: 1784

Answers (2)

Chandu
Chandu

Reputation: 331

  1. Select the stocklist.csv file in Solution Explorer and Set the "Copy to output Directory" property to "Copy always". So that stocklist.csv file will be copied to bin folder(output file)
  2. From the code you need to access the file by using the below line of code.

string CSV_FilePath = AppDomain.CurrentDomain.BaseDirectory + "stocklist.csv";

Upvotes: 3

user8045767
user8045767

Reputation:

"//stocklist.csv" would work in this case

Upvotes: 1

Related Questions