0

我一直在使用 Microsoft Live API 上传和下载数据库。但是在下载或上传后,如果我无论如何都尝试访问数据库,我的应用程序会给出 SqlCeException Unhandled & exits。如果我在访问数据库之前重新启动应用程序,它不会给出任何错误,所以现在解决方案是

重新启动应用程序

这是我的代码

    IsolatedStorageFileStream fileStream = null;

    private void Upload_Click(object sender, RoutedEventArgs e)
    {
        if (client == null || client.Session == null)
        {
            MessageBox.Show("You Must Sign In First.");
        }
        else
        {
            if (MessageBox.Show("Are You Sure? This Will Overwrite Your Old Backup File!", "Backup?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                UploadDatabase();
            }
        }
    }

    public void UploadDatabase()
    {
        if (SDFolderID != string.Empty)
        {
            WLInfo.Text = "Uploading Backup...";

            this.client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);

            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    fileStream = store.OpenFile("DB.sdf", FileMode.Open, FileAccess.Read);
                    client.UploadAsync(SDFolderID, "DB.sdf", fileStream, OverwriteOption.Overwrite);
                    WLInfo.Text = "Upload Complete.";
                }
            }
            catch
            {
                WLInfo.Text = "Error: Restart Application.";
            }
        }
    }

    private void ISFile_UploadCompleted(object sender, LiveOperationCompletedEventArgs args)
    {
        if (args.Error == null)
        {
            client = new LiveConnectClient(session);
            client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(GetFiles_GetCompleted);
            client.GetAsync(SDFolderID + "/files");
        }
        else
        {
            this.WLInfo.Text = "Error Uploading Backup File.";
        }
        fileStream.Close();
    }

    void GetFiles_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
    {
        List<object> data = (List<object>)e.Result["data"];

        foreach (IDictionary<string, object> content in data)
        {
            if (((string)content["name"]).Equals(FileName))
            {
                FileID = (string)content["id"];
            }
        }

        if (FileID != null)
        {
            WLInfo.Text = "Backup Found On Sky Drive.";
        }
        else
        {
            WLInfo.Text = "Backup Not Found On Sky Drive.";
        }
    }
4

1 回答 1

1

我猜它可能是 Stream 没有正确关闭,所以你的数据库文件仍然被锁定。当您上传或下载数据库文件时,请确保对所有一次性对象使用 using 语句,以便自动正确处理所有 Stream

在您的代码中 fileStream 未处理,这可能是导致问题的原因(您应该将此变量“保存”在本地文件中并在 ISFile_UploadCompleted 中对其调用处理)。

此外,如果您使用using,则无需在对象上调用 dispose (无需拥有store.Dispose();,当您超出使用范围时会自动完成)

于 2013-09-18T00:26:00.007 回答