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
相关产品推荐
相关产品推荐

