如何避免包含文件的完整路径

How to avoid including full path to file

我有一个包含在我的项目中的 .csv 文件。我创建了一个将路径作为参数的 StreamReader,但我必须包含文件的完整路径而不仅仅是文件名。

new StreamReader("products.csv"); 而不是

new StreamReader(@"C:\Users\user\Documents\Visual Studio 2015\Projects\Solution\Project\Products\products.csv");

如何使 StreamReader 只接受文件名而不是整个路径?

您可以将文件移动到您的 bin\debug 文件夹中并使用:

new StreamReader("products.csv");

您可以将根路径添加到配置

public class StreamReader
{
    private string _filePath;

    public StreamReader(string filePath)
    {
        _filePath = Path.IsPathRooted(filePath)
            ? filePath
            : Path.Combine(System.Configuration.ConfigurationManager.AppSettings["CsvRootPath"], filePath);
    }
}