How to read a text file in project's root directory?

前端 未结 7 810
走了就别回头了
走了就别回头了 2020-12-04 10:45

I want to read the first line of a text file that I added to the root directory of my project. Meaning, my solution explorer is showing the .txt file along side my .cs files

7条回答
  •  误落风尘
    2020-12-04 11:18

    private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
    

    The method above will bring you something like this:

    "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
    

    From here you can navigate backwards using System.IO.Directory.GetParent:

    _filePath = Directory.GetParent(_filePath).FullName;
    

    1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:

    _filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
    

    Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:

    _filePath += @"\myfile.txt";
    TextReader tr = new StreamReader(_filePath);
    

    Hope it helps.

提交回复
热议问题