2013-08-24 34 views
1

文件工作,所以我在XNA做了一個遊戲,並從文件中我做這樣的事情得到的分數......在MonoGame和Android

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?

回答

0

我認爲你正在尋找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; 
    } 
} 

我沒有測試過這一點,可能有辦法做到這一點在更少的代碼,但我沒有時間所以我只改變了你編碼最低要求金額。讓我知道事情的後續。

+0

這樣的作品,感謝,不知道IsolatedStorage,有用的東西。 –

0

你也可以使用外部目錄是這樣的:

定義類來存儲上下文:

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/