【问题标题】:Storing and retrieving data multiple time in locally saved json file windows phone 8.1 C#在本地保存的json文件windows phone 8.1 C#中多次存储和检索数据
【发布时间】:2015-09-16 19:56:01
【问题描述】:

您好,我将用户配置文件数据存储在移动内存本地的 items.json 文件中。 我正在创建一个文件夹,并在该文件夹中创建一个文件 (items.json)。

这是我的 add_profile 代码。

    //Profile_Class is My properties Class.
    List<Profile_Class> myprofile = new List<Profile_Class>();
    string filepath;
    StorageFile myfile;
    string jsonContents;
    public add_profile()
    {
        this.InitializeComponent();
        this.Loaded += SignUpPage_Loaded;
    }

    //When Page load I create a folder and a file in mobile memory.
    private async void SignUpPage_Loaded(object sender, RoutedEventArgs e)
    {
        StorageFolder myfolder = await KnownFolders.PicturesLibrary.CreateFolderAsync("TestFolder", CreationCollisionOption.OpenIfExists);
        myfile = await myfolder.CreateFileAsync("items.json", CreationCollisionOption.OpenIfExists);
    }

上面的代码创建一个文件夹和文件。 现在下一步。

    private List<Profile_Class> buildObjectGraph()
    {
        myprofile.Add(new Profile_Class() { id = ProType.Text, address = address.Text, category = ProType.Text, color = "#31b1b0", company = company.Text, email = email.Text, facebook = facebok.Text, firstName = fname.Text, image = "Waiting", lastName = lname.Text, linkedin = linkdin.Text, mobile = phone.Text, pin = pin.Text, title = title.Text, twitter = twiter.Text, website = website.Text, work = phone_other.Text });

        return myprofile;
    }
    private async Task WritejsonAsync()
    {
        var mydata = buildObjectGraph();


        jsonContents = JsonConvert.SerializeObject(mydata);
        using (IRandomAccessStream mysteream = await myfile.OpenAsync(FileAccessMode.ReadWrite))
        {

            using (DataWriter textWriter = new DataWriter(mysteream))
            {
                textWriter.WriteString(jsonContents);
                await textWriter.StoreAsync();
            }
            this.Frame.Navigate(typeof(MainPage));

        }
     }

    private async Task readjsonAsync()
    {

        string jsonview = JsonConvert.SerializeObject(myprofile);

        using (IRandomAccessStream textStream = await myfile.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (DataWriter textWriter = new DataWriter(textStream))
            {
                textWriter.WriteString(jsonview);

                await textWriter.StoreAsync();
            }
            MessageDialog readmesg = new MessageDialog(jsonview);
            await readmesg.ShowAsync();
        }
    }

我在 xaml 中有文本框。以及保存和读取按钮事件。

    private async void read_click(object sender, RoutedEventArgs e)
    {

        await readjsonAsync();
    }

    private async void Save_data(object sender, RoutedEventArgs e)
    {
        await WritejsonAsync();

    }

代码对于单个输入来说很好,,,而我又回来了,然后每次创建新文件我想。我如何检查文件是否已经存在,然后将其保存在 myfile 中,然后再保存新条目。

读取按钮也是如此,当我来自另一个页面时,数据会丢失。并且每次都显示空白 Json。我希望每次进入此屏幕时,我都可以在相同的 json 值中添加新值并检索所有以前的值。你能解决这个问题吗?

【问题讨论】:

  • 您是在说您不知道如何使用 System.IO 类来检查文件是否存在.. 同样在您的代码中,为什么您声明了一些东西,但在您的代码中却没有张贴你曾经在这一行中使用过变量吗 `var mydata = buildObjectGraph();` buildObjectGraph 方法是什么样的?你熟悉调试器..?开始调试代码听起来你需要在某处声明一个静态和/或公共变量..如果每次页面加载它都会重新初始化特定变量..
  • 是的,您是对的,请您指导我如何检查文件是否存在。?在代码中,我只是选择了 OpenIfExist,但结果是 myfile 第二次保持为空。
  • if(File.Exists(path){ } 当然 path 在你的情况下是变量名/路径 myfile 假设 myfile has full path + file name 如果你需要检查初始负载之外的其他位置然后移动然后更改字符串 myfile 到 public string myfile = string.Empty 最初或使其成为静态
  • 我为愚蠢的事情道歉。但试图解决这个问题。我已将 myfile 更改为 static,,,我得到了文件路径。 if(File.Exists(path){} 什么是文件,文件名在当前上下文中不存在?

标签: c# json windows-phone-8.1 windows-store-apps persistence


【解决方案1】:

使用此代码检查文件是否存在

public async Task<bool> FileExist(string FileName)
        {
            try
            {
                var folders = ApplicationData.Current.LocalFolder;
                var file = await folders.GetFileAsync(Path);
                if (file.Path != null)
                    return false;
                else
                    return true;
            }
            catch
            {
                return true;

            }
        }

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多