在删除之前,在IsolatedStorage中“关闭”文件

时间:2012-06-06 19:26:15

标签: c# silverlight windows-phone-7

我正在为Windows Phone 7编写一个应用程序,我将图像保存到隔离存储。 当我加载它们时,我无法关闭打开的图像流,因为我的程序的其他部分需要能够读取它们才能正确显示图像。 当我准备在隔离存储中删除/更改文件时,我只想关闭这些流。

然而,当我准备删除这些图像时,我无法再访问我打开它时使用的本地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 个答案:

答案 0 :(得分:3)

除非您处理大量数据,否则应在将文件流加载到内存后立即关闭文件流。例如,如果您正在加载图像,则应在创建图像对象后关闭流。

相关问题