Monogame游戏中读取.txt高分文件返回空字符串问题求助
Monogame读取highscore.txt返回空字符串的排查与解决
确认文件实际内容非空
直接打开Debug文件夹下的highscore.txt,手动检查是否存在有效内容——有时文件可能因写入失败、误操作被清空。验证当前工作目录指向
在代码中打印当前工作目录,确认是否为预期的Debug路径:Debug.WriteLine($"Current Directory: {currentDirectory}");Monogame运行时的工作目录可能与项目输出目录不一致,比如指向项目根目录而非Debug文件夹。
改用程序集路径获取输出目录
替换Directory.GetCurrentDirectory(),改用程序集所在路径来定位文件,避免工作目录偏差:using System.Reflection; private void ReadFile(string fileName) { try { string exePath = Assembly.GetExecutingAssembly().Location; string exeDirectory = Path.GetDirectoryName(exePath); string filePath = Path.Combine(exeDirectory, fileName); string fileContent = File.ReadAllText(filePath); Debug.WriteLine(fileContent); } catch (ArgumentException ex) { Debug.WriteLine("blank or zero length"); } catch (Exception ex) { Debug.WriteLine($"An error occurred: {ex.Message}"); } }确保文件被复制到输出目录
在Visual Studio中右键highscore.txt文件,打开属性面板,将复制到输出目录设置为「始终复制」或「如果较新则复制」,保证编译时文件被同步到Debug文件夹。明确指定编码读取
即使确认是UTF8编码,也可以在读取时明确指定,避免编码自动识别偏差:string fileContent = File.ReadAllText(filePath, Encoding.UTF8);检查文件是否被锁定
如果之前有写入操作未正确释放资源,可能导致文件被锁定,读取返回空。写入时务必用using语句确保流被正确关闭:using (StreamWriter sw = new StreamWriter(filePath)) { sw.Write("your highscore data"); }
内容的提问来源于stack exchange,提问作者Sophia
相关产品推荐
相关产品推荐

