0

我正在编写一个单元测试来验证对象的序列化,并且我能够成功保存文件而没有任何问题。我什至可以浏览文件并验证内容是否正确。但是,当我尝试打开文件进行阅读时,我总是收到 UnauthorizedAccess 异常。

这是用于保存项目的代码:

        public static async Task SaveItem<T>(string folderName, T item)
        where T : BaseBusinessItem
    {
        if (string.IsNullOrEmpty(folderName))
        {
            throw new ArgumentNullException("folderName");
        }

        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        try
        {
            var folder = await ApplicationData.Current.LocalFolder
                                             .CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
            var file =
                await
                folder.CreateFileAsync(item.UniqueID.GetHashCode().ToString(), CreationCollisionOption.ReplaceExisting);
            var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
            using (var outStream = stream.GetOutputStreamAt(0))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(outStream.AsStreamForWrite(), item);
                await outStream.FlushAsync();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }

这是用于恢复项目的代码:

    public static async Task<T> RestoreItem<T>(string folderName, string hashCode)
        where T : BaseBusinessItem, new()
    {
        if (string.IsNullOrEmpty(folderName))
        {
            throw new ArgumentNullException("folderName");
        }

        if (string.IsNullOrEmpty(hashCode))
        {
            throw new ArgumentNullException("hashCode");
        }

        var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(folderName);
        var file = await folder.GetFileAsync(hashCode);
        var inStream = await file.OpenSequentialReadAsync();
        var serializer = new DataContractJsonSerializer(typeof(T));
        var retVal = (T)serializer.ReadObject(inStream.AsStreamForRead());
        return retVal;
    }

和单元测试:

    [TestMethod]
    public async Task TestFileSaveLoad()
    {
        await _ds.SaveItem("TestFolder");
        Guid ID = _item.UniqueID;
        _ds = await ItemDataSource.LoadItem("TestFolder", ID.GetHashCode().ToString());
    }

我可能遗漏的任何想法或故障排除步骤。单元测试应用清单包括以下功能:文档库、Internet(客户端)。以下声明已到位:文件打开选择器、文件保存选择器和文件类型关联。

谢谢!

4

1 回答 1

0

这个代码片段帮助我实现了我的目标。希望这对其他人有帮助:

http://codepaste.net/gtu5mq

于 2012-11-26T20:44:23.630 回答