简体   繁体   中英

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.

在此处输入图像描述

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.

  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";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM