我需要读写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;
}
}
}
谢谢你的帮助
答案 0 :(得分:3)
您不希望在MemoryStream
声明中使用LoadToStorage
方法创建using
,因为大概是调用者不希望您交回一个Dispose
d:
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;
}
}