我正在为Windows Phone 7编写一个应用程序,将图像保存到独立存储中。 当我加载它们时,我无法关闭打开的图像流,因为我的程序的其他部分需要能够读取它们才能正确显示图像。 我只想在我准备在隔离存储中删除/更改文件本身时关闭这些流。删除它们之前在IsolatedStorage中“关闭”文件
但是,当我准备好删除这些图像时,我不再有权访问当我打开它们时使用的本地IsolatedStorageFileStream变量。
有没有办法以某种方式“关闭”这些文件在这一点上(除了重新启动我的应用程序)?否则,我似乎无法删除它们。
这是我写的图像转换成IsolatedStorage:
Dictionary<string, Stream> imageDict = (Dictionary<string, Stream>)Globals.CNState["ATTACHMENT"];
foreach (string pic in imageDict.Keys)
{
Stream input = imageDict[pic];
input.Position = 0;
byte[] buffer = new byte[16*1024];
using (FileStream thisStream = myISF.OpenFile(thisDirectory + pic, FileMode.Create))
{
int read = input.Read(buffer, 0, buffer.Length);
while (read > 0)
{
thisStream.Write(buffer, 0, read);
read = input.Read(buffer, 0, buffer.Length);
}
}
}
我这是怎么加载出来后(如你所看到的,我让他们开):
string[] storedImages = myISF.GetFileNames(thisDirectory);
if(storedImages.Length > 0)
{
foreach(string pic in storedImages)
{
IsolatedStorageFileStream imageStream = myISF.OpenFile(thisDirectory + pic, FileMode.Open, FileAccess.Read, FileShare.Read);
imageDict.Add(pic, imageStream);
}
}
Globals.CNState["ATTACHMENT"] = imageDict;
我可以因为我的应用程序的另一部分需要从它们的文件流创建图像(这可能需要发生多次):
if (Globals.CNState != null && Globals.CNState.ContainsKey("ATTACHMENT"))
{
imageDict = (Dictionary<string, Stream>)Globals.CNState["ATTACHMENT"];
foreach (string key in imageDict.Keys)
{
Stream imageStream = imageDict[key];
Image pic = new Image();
pic.Tag = key;
BitmapImage bmp = new BitmapImage();
bmp.SetSource(imageStream);
pic.Source = bmp;
pic.Margin = new Thickness(0, 0, 0, 15);
pic.MouseLeftButtonUp += new MouseButtonEventHandler(pic_MouseLeftButtonUp);
DisplayPanel.Children.Add(pic);
}
}
我还需要保持流打开,因为我的程序的另一部分将这些图像发送到服务器,并据我所知,我只能发送字节流,而不是UIElement。
请张贴您的代码 - 您如何编写这些文件? – Oded
通过保持流打开,您违背了IsolatedStorage(临时和快速访问)的基本原则。如果它是一个Win Forms应用程序(或者你将用完文件句柄),那么你永远不会考虑这么做,那么为什么它会在资源严重有限的设备上执行?您应该缓存位图或根据需要重新打开流(大多数应用程序按需重新加载图像,有些缓存一些经常使用的位图):) –