2017-06-22 18 views
0

私はXamarin.Forms(フォーム部分は無関係です)アプリで作業していて、PCLStorage Xamarinプラグインを使ってJSON文字列をテキストファイルに保存しようとしています。インターネット接続が利用できない場合に備えて、テキストファイルがキャッシュされたデータのためにそこにあります。Xamarin PCLStorageがテキストファイルを書き込んだり読んでいない

すべてのプロジェクト(PCL、iOS、Android、UWP)にプラグインを追加しました。ポータブルクラスに次のコードを追加しました。

using PCLStorage; 

namespace DailyBibleReading 
{ 
    public class Helper 
    { 
     // read a text file from the app's local folder 
     public static async Task<string> ReadTextFileAsync(string _filename) 
     { 
      // declare an empty variable to be filled later 
      string result = null; 

      // see if the file exists 
      try 
      { 
       // get hold of the file system 
       IFolder rootFolder = FileSystem.Current.LocalStorage; 

       // create a folder, if one does not exist already 
       //IFolder folder = await rootFolder.CreateFolderAsync("DailyBibleReading", CreationCollisionOption.OpenIfExists); 

       // create a file, overwriting any existing file 
       IFile file = await rootFolder.CreateFileAsync(_filename, CreationCollisionOption.ReplaceExisting); 

       // populate the file with some text 
       result = await file.ReadAllTextAsync(); 
      } 
      // if the file doesn't exist 
      catch (Exception ex) 
      { 
       // Output to debugger 
       Debug.WriteLine(ex); 
      } 

      // return the contents of the file 
      return result; 
     } 

     // write a text file to the app's local folder 
     public static async Task<string> WriteTextFileAsync(string _filename, string _content) 
     { 
      // declare an empty variable to be filled later 
      string result = null; 
      try 
      { 
       // get hold of the file system 
       IFolder rootFolder = FileSystem.Current.LocalStorage; 

       // create a folder, if one does not exist already 
       //IFolder folder = await rootFolder.CreateFolderAsync("DailyBibleReading", CreationCollisionOption.OpenIfExists); 

       // create a file, overwriting any existing file 
       IFile file = await rootFolder.CreateFileAsync(_filename, CreationCollisionOption.ReplaceExisting); 

       // populate the file with some text 
       await file.WriteAllTextAsync(_content); 

       result = _content; 
      } 
      // if there was a problem 
      catch (Exception ex) 
      { 
       // Output to debugger 
       Debug.WriteLine(ex); 
      } 

      // return the contents of the file 
      return result; 
     } 
    } 
} 

CreateFolderAsyncセクションがコメントアウトされていることがあります。私は、アプリケーションのフォルダ内に別のフォルダを作成する必要はないと感じました。私は両方の方法で試してみましたが、それが必要な場合に備えてです。いずれの方法でも働かなかった。 LocalStorageが使用中であることに気付くかもしれません。私も同じ結果を持ってRemoteStorageを試しました。

JSON文字列を取得したときに、それらのメソッドを呼び出します。

string result = null; 

// make the api call 
result = await Helper.GetHttpStringAsync("http://www.anti-exe.com/api/dailybiblereading?begindate=" + _begindate + "&enddate=" + _enddate + "&version=" + _version); 

string textfile = "ApiResults.txt"; 
// if there is no content 
if (result == null || result == "" || result.Contains("SQLSTATE") == true) 
{ 
    // read content from a pre-existing file 
    result = await Helper.ReadTextFileAsync(textfile); 
    // Output to debugger 
    Debug.WriteLine("Can't connect to the API." + "\r\n" + "Loading from local cache."); 
} 
else 
{ 
    // write to a cache file 
    await Helper.WriteTextFileAsync(textfile, result); 
} 

すべてがかなり簡単なようです(私のネイティブのWindows 10コードではうまくいくとは言えません)。 JSONを試してみてください。何もない場合(インターネットやAPIがダウンしていない場合)、キャッシュからJSON文字列を取得します。 JSONがある場合は、キャッシュに書き込んでください。

実際にはファイルに書き込まれていないと仮定します。実際にそのファイルの内容をチェックする方法はわかりません(メモ帳を開いて読み込むことはできません)。

私はアプリを開きます。私はアプリを閉じる。私はインターネットアクセスを削除します。私はアプリを開きます。すべて完了したら、resultは空です(result == "")。

+1

まあ、彼らはこの目的のために正確にデバッガを発明しました:-) あなたのアプリケーションをデバッガで開き、コードをステップバイステップで実行してください... "仮定"をしないでください。 – Grisha

+0

デバッガでテキストファイルを開くことはできますか? – doubleJ

+0

いいえ、そこに何バイトありますか、書き込む回数は何か、例外はありますか、既存のファイルを上書きするかどうかはわかります。推測の代わりにたくさん - 。 – Grisha

答えて

1

問題がコード内に明確にコメントされています。

// create a file overwriting any existing file 
IFile file = await rootFolder.CreateFileAsync(_filename, CreationCollisionOption.ReplaceExisting); 

//ファイルが存在するのであれば、あなたはそれを捨てると新しいものを作っている既存のファイル

を上書きしたファイルを作成します。その後、新しいファイルからテキストを読み込み、そこには何もありません。ファイルのオープン方法としてCreationCollisionOption.OpenIfExistsを試してみてください。

+0

興味深い...私はPCLStorageのドキュメントから直接コピー/ペーストを使用していました。 Hehehe ...たぶん彼らは私が同じではないそれを使用していた。 – doubleJ

+1

コピーパスタの危険 –

+0

私は 'ReadTextFileAsync()'の 'ReplaceExisting'だけを変更しました。キャッシュされた最後の成功した結果セットだけが必要なので、それぞれの書き込みの前に置き換えます。 – doubleJ

関連する問題