我如何读取具有自定义路径的TXT文件,但是“通用”任何计算机用户的路径?

发布于 2025-01-31 09:37:07 字数 361 浏览 2 评论 0原文

我想在不使用bin/debug文件夹的情况下阅读文本文件(.txt),因为我必须将项目推入github,我需要我的文本文件(.txt)的路径(.txt)一个是解决方案中的文件夹。路径格式必须适用于任何计算机,我的计算机的完整路径不好。

using (System.IO.StreamReader srr = new System.IO.StreamReader(@"C:\example\example\example\example\example\example\FolderInSolution\highscoreFile.txt"))
displayHighScore.Content = srr.ReadLine();

I would like to read a text file(.txt) without using bin/debug folder, because I have to push the project into github, and I need a path for my text file(.txt) which one is a folder in the solution. The path format must works for any computer, full path from my computer is not good.

using (System.IO.StreamReader srr = new System.IO.StreamReader(@"C:\example\example\example\example\example\example\FolderInSolution\highscoreFile.txt"))
displayHighScore.Content = srr.ReadLine();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笨笨の傻瓜 2025-02-07 09:37:07

我看到了为您看到的两个选项,即:

  1. 使用相对路径并将您的文件直接放在根文件夹中,例如:
.
├── dotnet.csproj
├── highscoreFile.txt
└── Program.cs

您可以删除大多数文件路径:

using (System.IO.StreamReader srr = new System.IO.StreamReader(@"highscoreFile.txt")) {
    Console.WriteLine(srr.ReadLine());
}

  1. 使用每个用户可以使用的环境变量来指示您的文件位置是:
string path = Environment.GetEnvironmentVariable("HIGH_SCORE_FILE")
using (System.IO.StreamReader srr = new System.IO.StreamReader(path)) {
    Console.WriteLine(srr.ReadLine());
}

I see two options for you, namely:

  1. Use a relative path and place your file directly in the root folder, for example:
.
├── dotnet.csproj
├── highscoreFile.txt
└── Program.cs

Then you could remove most of that file path:

using (System.IO.StreamReader srr = new System.IO.StreamReader(@"highscoreFile.txt")) {
    Console.WriteLine(srr.ReadLine());
}

  1. Use an environment variable that each user could use to indicate where your file is:
string path = Environment.GetEnvironmentVariable("HIGH_SCORE_FILE")
using (System.IO.StreamReader srr = new System.IO.StreamReader(path)) {
    Console.WriteLine(srr.ReadLine());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文