You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#游戏本地排行榜问题:无法访问嵌入式文本文件

解决C#本地排行榜文件访问问题

核心问题分析

你把Scoreboard.txt放在资源文件夹,但代码里用的是FileSystem.AppDataDirectory——这两个是完全不同的位置:

  • 资源文件夹里的文件是嵌入程序包的只读文件,无法直接写入;
  • AppDataDirectory是当前用户的应用数据目录,是存储用户可读写数据的正确位置,但你之前的资源文件并没有在这里,所以读取不到内容。

修正方案

1. 首次运行时将资源文件复制到AppData目录

如果需要保留初始排行榜数据,先把资源文件复制到可读写的AppData目录,之后的读写都操作这个副本:

string fileName = "Scoreboard.txt";
// 资源文件的路径(根据项目类型调整,比如MAUI是Resources文件夹,WPF是Properties.Resources对应路径)
string resourcePath = Path.Combine(AppContext.BaseDirectory, "Resources", fileName);
string targetPath = Path.Combine(FileSystem.AppDataDirectory, fileName);

// 首次运行时复制资源文件到目标目录
if (!File.Exists(targetPath))
{
    File.Copy(resourcePath, targetPath);
}

// 写入操作
using (StreamWriter writer = new StreamWriter(targetPath, true))
{
    writer.WriteLine(balance.ToString());
}

// 读取操作
using (StreamReader reader = new StreamReader(targetPath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        if (int.TryParse(line, out int score))
        {
            LeaderBoard.Add(score);
        }
    }
}

2. 直接在AppData目录创建新文件(无初始数据)

如果不需要初始数据,直接在AppData目录创建文件即可,无需依赖资源文件夹:

string fileName = "Scoreboard.txt";
string filePath = Path.Combine(FileSystem.AppDataDirectory, fileName);

// 写入时文件不存在会自动创建
using (StreamWriter writer = new StreamWriter(filePath, true))
{
    writer.WriteLine(balance.ToString());
}

// 读取前先判断文件是否存在,避免报错
if (File.Exists(filePath))
{
    using (StreamReader reader = new StreamReader(filePath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (int.TryParse(line, out int score))
            {
                LeaderBoard.Add(score);
            }
        }
    }
}

额外优化建议

  • 用int.TryParse替代Convert.ToInt32,避免文件内容格式错误导致程序崩溃;
  • 右键资源文件夹里的Scoreboard.txt→属性,将生成操作设为“内容”,复制到输出目录设为“如果较新则复制”,确保资源文件能被复制到程序运行目录。

内容的提问来源于stack exchange,提问作者thedrooster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 03:07:08