How to read existing text files without defining path

后端 未结 8 999
太阳男子
太阳男子 2020-12-14 05:53

Most of the examples shows how to read text file from exact location (f.e. \"C:\\Users\\Owner\\Documents\\test1.txt\"). But, how to read text files without writing full path

相关标签:
8条回答
  • 2020-12-14 06:31

    When you provide a path, it can be absolute/rooted, or relative. If you provide a relative path, it will be resolved by taking the working directory of the running process.

    Example:

    string text = File.ReadAllText("Some\\Path.txt"); // relative path
    

    The above code has the same effect as the following:

    string text = File.ReadAllText(
        Path.Combine(Environment.CurrentDirectory, "Some\\Path.txt"));
    

    If you have files that are always going to be in the same location relative to your application, just include a relative path to them, and they should resolve correctly on different computers.

    0 讨论(0)
  • 2020-12-14 06:34

    If your application is a web service, Directory.CurrentDirectory doesn't work.

    Use System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "yourFileName.txt")) instead.

    0 讨论(0)
提交回复
热议问题