【问题标题】:How to avoid including full path to file如何避免包含文件的完整路径
【发布时间】:2016-09-10 21:40:04
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# file path streamreader


    【解决方案1】:

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

    new StreamReader("products.csv");
    

    【讨论】:

    • @jmkjaer 不客气。如果您查看项目的属性,则有一个名为 Build Events 的部分,您可以在此处添加一个宏以在构建项目时自动将文件复制到您的 bin。
    【解决方案2】:

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

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

    【讨论】:

    • 我将不得不尝试一下,看看它有什么作用。不过现在,我会接受克林特的回答。不过谢谢!
    猜你喜欢
    • 2011-01-08
    • 1970-01-01
    • 2014-05-09
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2019-01-14
    相关资源
    最近更新 更多