【问题标题】:Windows Phone 8 append to JSON fileWindows Phone 8 附加到 JSON 文件
【发布时间】:2014-04-22 19:45:50
【问题描述】:

我正在开发一个 Windows Phone 8 应用程序。 我在附加到我的 JSON 文件时遇到问题。
如果我保持应用程序打开,它工作正常,但是一旦我关闭它并返回它,它就会从文件的开头重新开始写入。

相关代码:

private async void btnSave_Click(object sender, RoutedEventArgs e)
{
    // Create a entry and intialize some values from textbox...
    GasInfoEntries _entry = null;
    _entry = new GasInfoEntries();
    _entry.Gallons = TxtBoxGas.Text;
    _entry.Price = TxtBoxPrice.Text;
    _GasList.Add(_entry);

    //TxtBlockPricePerGallon.Text = (double.Parse(TxtBoxGas.Text) / double.Parse(TxtBoxPrice.Text)).ToString();

    // Serialize our Product class into a string    
    string jsonContents = JsonConvert.SerializeObject(_GasList);

    // Get the app data folder and create or open the file we are storing the JSON in.            
    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
    StorageFile textfile = await localFolder.CreateFileAsync("gasinfo.json", CreationCollisionOption.OpenIfExists); //if get await operator error add async to class (btnsave)

    //open file
    using (IRandomAccessStream textstream = await textfile.OpenAsync(FileAccessMode.ReadWrite))
    {
        //write JSON string
        using (DataWriter textwriter = new DataWriter(textstream))
        //using (DataWriter textwriter = new DataWriter(textstream))
        {
            textwriter.WriteString(jsonContents);
            await textwriter.StoreAsync(); //writes buffer to store
        }
    }
}

private async void btnShow_Click(object sender, RoutedEventArgs e)
{
    StorageFolder localfolder = ApplicationData.Current.LocalFolder;
    try
    {
        // Getting JSON from file if it exists, or file not found exception if it does not
        StorageFile textfile = await localfolder.GetFileAsync("gasinfo.json");

        using (IRandomAccessStream textstream = await textfile.OpenReadAsync())
        {
            //read text stream
            using (DataReader textreader = new DataReader(textstream))
            {
                //get size ...not sure what for  think check the file size (lenght) then based on next 2 commands waits until its all read
                uint textlength = (uint)textstream.Size;
                await textreader.LoadAsync(textlength);
                //read it
                string jsonContents = textreader.ReadString(textlength);
                // deserialize back to gas info
                _GasList = JsonConvert.DeserializeObject<List<GasInfoEntries>>(jsonContents) as List<GasInfoEntries>;

                displayGasInfoEntries();

            }
        }
    }
    catch
    {
        txtShow.Text = "something went wrong";
    }      
}

private void displayGasInfoEntries()
{
    txtShow.Text = "";
    StringBuilder GasString = new StringBuilder();
    foreach (GasInfoEntries _entry in _GasList)
    {
        GasString.AppendFormat("Gallons: {0} \r\n Price: ${1} \r\n", _entry.Gallons, _entry.Price); // i think /r/n means Return and New line...{0} and {1} calls "variables" in json file
    }
    txtShow.Text = GasString.ToString();
}

谢谢

【问题讨论】:

  • 您是否在真实设备上测试您的应用程序?如果不是:请记住,每次关闭模拟器时,您保存在此模拟器及其应用程序中的所有设置/数据都消失了。所以如果你使用模拟器:不要每次都关闭它。
  • 是的,我正在手机上进行测试。看起来一旦我关闭并重新打开应用程序,它就会从文件的开头开始重写,而不是追加到结尾。

标签: json windows-phone-8 datareader storagefile


【解决方案1】:

您每次启动应用程序时都会拨打btnShow_Click 吗?因为否则_GasList 将为空;如果您现在拨打btnSave_Click,所有之前所做的更改都将丢失。

因此,请确保在将项目添加到 _GasList 之前恢复之前保存的 json 数据。

【讨论】:

  • 好的...取得进展..我重新启动应用程序添加数据(保存它)关闭应用程序单击显示按钮然后添加更多数据并写入文件末尾! (我的应用程序中没有显示按钮 - 它用于测试)所以我想我需要先合并文件的读取(也许在初始化时?)我希望数据已经列在历史记录中应用程序加载时的页面。那是因为……谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多