2012-06-06 62 views
-1

我正在为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。

+1

请张贴您的代码 - 您如何编写这些文件? – Oded

+0

通过保持流打开,您违背了IsolatedStorage(临时和快速访问)的基本原则。如果它是一个Win Forms应用程序(或者你将用完文件句柄),那么你永远不会考虑这么做,那么为什么它会在资源严重有限的设备上执行?您应该缓存位图或根据需要重新打开流(大多数应用程序按需重新加载图像,有些缓存一些经常使用的位图):) –

回答

3

除非你处理海量数据大小,否则只要将它们加载到内存中,就应该关闭文件流。例如,如果您正在加载图像,则应在创建图像对象后关闭流。

+0

我需要流保持打开状态,因为我的程序的多个部分依赖于它们开放运作。相信我,我不希望它以这种方式工作,但这是它能够工作的唯一方式。请回答我的实际问题,即如果有方法可以关闭文件而不访问用于打开它们的原始流对象。 – WinterRye

+0

@WinterRye ...文件需要保持打开才能用作图像......因为它们必须完全加载到*内存位图*中才可见。他们已经加载后可以关闭流。 –

+0

@WinterRye - 直接回答:没有。间接回答:你有没有考虑将数据加载到一个'MemoryStream'中,并将_that_作为Stream传递? –