0

我需要读写一个 MemoryStream 我编写了这个方法,但我在加载方法上有一个错误:

    public async void SaveToStorage(MemoryStream stream, String filename)
    {
        var localFolder = ApplicationData.Current.LocalFolder;
        var storageFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

        using (Stream x = await storageFile.OpenStreamForWriteAsync())
        {
            x.Seek(0, SeekOrigin.Begin);
            stream.WriteTo(x);
        }
    }

以及有问题的方法(我认为):

public async Task<MemoryStream> LoadToStorage(string filename)
{
    var localFolder = ApplicationData.Current.LocalFolder;
    var storageFile = await localFolder.GetFileAsync(filename);

    using (var fileStream = await storageFile.OpenStreamForReadAsync())
    {
        using (var memoryStream = new MemoryStream())
        {
            await fileStream.CopyToAsync(memoryStream);

            memoryStream.Seek(0, SeekOrigin.Begin);
            return memoryStream;
        }
    }
}

谢谢你的帮助

4

1 回答 1

5

您不想让MemoryStream您在声明中的LoadToStorage方法中创建using,因为大概调用者不希望您交回一个已被Disposed 的对象:

public async Task<MemoryStream> LoadToStorage(string filename)
{
    var localFolder = ApplicationData.Current.LocalFolder;
    var storageFile = await localFolder.GetFileAsync(filename);

    using (var fileStream = await storageFile.OpenStreamForReadAsync())
    {
        var memoryStream = new MemoryStream();
        await fileStream.CopyToAsync(memoryStream);

        memoryStream.Seek(0, SeekOrigin.Begin);
        return memoryStream;
    }
}
于 2014-04-25T14:37:43.847 回答