【问题标题】:Working with files in MonoGame and Android在 MonoGame 和 Android 中处理文件
【发布时间】:2013-08-24 23:56:24
【问题描述】:

所以我在 XNA 中制作了一个游戏,为了从文件中获取分数,我做了这样的事情......

private void GetScore()
    {
        if (File.Exists(scoreFilename))
        {
            using (StreamReader sr = new StreamReader(scoreFilename))
            {
                hiScore = Convert.ToInt16(sr.ReadLine());
            }
        }
        else
        {
            FileStream fs = File.Create(scoreFilename);
            fs.Close();
            using (StreamWriter sw = new StreamWriter(scoreFilename))
            {
                sw.Write("0");
            }
            hiScore = 0;
        }
    }

这适用于 Windows,但我如何在 Android 上做到这一点?

【问题讨论】:

    标签: android monogame


    【解决方案1】:

    我认为您正在寻找IsolatedStorageFile。它应该与writing data on Windows Phone 一样工作。您的新代码可能如下所示:

    private void GetScore()
    {
        var store = IsolatedStorageFile.GetUserStoreForApplication();
    
        if (store.FileExists(scoreFilename))
        {
            var fs = store.OpenFile(scoreFilename, FileMode.Open);
            using (StreamReader sr = new StreamReader(fs))
            {
                hiScore = Convert.ToInt16(sr.ReadLine());
            }
        }
        else
        {        
            var fs = store.CreateFile(scoreFilename);            
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write("0");
            }
            hiScore = 0;
        }
    }
    

    我还没有对此进行测试,并且可能有一种方法可以用更少的代码来完成,但我没有时间,所以我只将您的代码更改为所需的最低数量。告诉我进展如何。

    【讨论】:

    • 那行得通,谢谢,不知道IsolatedStorage,有用的东西。
    【解决方案2】:

    你也可以像这样使用外部目录:

    定义类来存储上下文:

    public class App
    {        
        public static Context CurentContext { get; set; }
    }
    

    在主要活动上,初始化上下文:

    public class Activity1 : Microsoft.Xna.Framework.AndroidGameActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);            
    
                App.CurentContext = this;
    
                var g = new Game1();
                SetContentView((View)g.Services.GetService(typeof(View)));
                g.Run();
            }
        }
    

    然后访问外部目录:

    var dirPath = App.CurentContext.GetExternalFilesDir(string.Empty).AbsolutePath;
    string filePath = Path.Combine(dirPath, "YourScoreFileName.txt");
    using (var stream = File.OpenRead(filePath))
    {
    
    }
    

    并且文件应该存储在这样的位置:

    /storage/emulated/0/Android/data/[your_package]/files/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2014-01-30
      相关资源
      最近更新 更多