在Windows 8 Store App中从文件中检索数据

时间:2014-07-30 12:23:47

标签: windows-store-apps windows-store

我创建了一个应用程序,我已成功在文件中写入详细信息。但是从应用程序访问文件时,我得到以下例外情况:

enter image description here

以下是我的课程:

public class UserDetails
{
    public string Name { get; set; }
    public string Course { get; set; }
    public string City { get; set; }
}

以下是我的代码,用于编写和读取文件:

private async void btnSearch_Click(object sender, RoutedEventArgs e)
    {
        details.Name = TxtName.Text;
        details.Course = TxtCouse.Text;
        details.City = TxtCity.Text;
        await SaveAsync();
        this.Frame.Navigate(typeof(string));
    }

    private async Task SaveAsync()
    {
        StorageFolder localfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Storage Application", CreationCollisionOption.OpenIfExists);
        StorageFile sampleFile = await localfolder.CreateFileAsync("UserDetails", CreationCollisionOption.ReplaceExisting);
        IRandomAccessStream stream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite);
        using(IOutputStream outstream = stream.GetOutputStreamAt(0))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetails));
            serializer.WriteObject(outstream.AsStreamForWrite(), details);
            await outstream.FlushAsync();
        }
        await RestoreDataAsync();
    }

    private async Task RestoreDataAsync()
    {
        StorageFolder localfolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Storage Application");
        StorageFile sampleFile = await localfolder.GetFileAsync("UserDetails");
        IRandomAccessStream inStream = await sampleFile.OpenAsync(FileAccessMode.Read);
        DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetails));
        var Details = (UserDetails)serializer.ReadObject(inStream.AsStreamForRead());
        inStream.Dispose();
        TblName.Text = details.Name;
        TblCourse.Text = details.Course;
        TblCity.Text = details.City;
    }

我是创建Windows应用商店应用的新手。

1 个答案:

答案 0 :(得分:0)

问题是你的SaveAsync()方法,你打开了sampleFile的StorageFile,但是没有处理它。使用后尝试添加sampleFile.Dispose();