获取IsolatedStorageException:IsolatedStorageFileStream上不允许操作

时间:2012-05-01 20:09:09

标签: c# windows-phone-7

我在以下代码中遇到上述异常和错误,这是为了从隔离存储中播放选定的mp3文件:

using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{            
     using (var isfs = isf.OpenFile(selected.Path, FileMode.Open))
     {                        
          this.media.SetSource(isfs);              
          isfs.Close();                        
     }                    
     isf.Dispose();
}

错误是如此模糊,以至于我不确定会出现什么问题......我可以检查的任何想法或至少是这个错误的常见来源?

编辑:抛出异常:using(var isfs = isf.OpenFile(...))

编辑2:堆栈跟踪......

at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, IsolatedStorageFile isf)
at Ringify.Phone.PivotContent.RingtoneCollectionPage.MediaIconSelected(Object sender, GestureEventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)

我也意识到,如果我播放一首歌然后停止它(UI中有播放和暂停按钮),则不会发生错误,然后播放另一首歌。当我播放一首歌曲,停止播放并尝试再次播放同一首歌时,就会发生这种情况。

2 个答案:

答案 0 :(得分:8)

当您播放相同的音乐两次时会出现问题,因此可能是文件共享问题。您应该尝试提供OpenFile方法的FileShare参数:

var isfs = isf.OpenFile(selected.Path, FileMode.Open, FileShare.Read)

虽然我不明白为什么会发生这种情况,因为你明确关闭了文件。

编辑:好的,用Reflector做了一些挖掘,我发现了。 MediaElement.SetSource的代码是:

public void SetSource(Stream stream)
{
    if (stream == null)
    {
        throw new ArgumentNullException("stream");
    }
    if (stream.GetType() != typeof(IsolatedStorageFileStream))
    {
        throw new NotSupportedException("Stream must be of type IsolatedStorageFileStream");
    }
    IsolatedStorageFileStream stream2 = stream as IsolatedStorageFileStream;
    stream2.Flush();
    stream2.Close();
    this.Source = new Uri(stream2.Name, UriKind.Absolute);
}

所以基本上它不会使用你提供的流,它甚至会关闭它。但它保留了文件的名称,我猜它会在播放音乐时重新打开它。因此,如果您在播放音乐时尝试重新打开具有独占访问权限的同一文件,则会因MediaElement打开文件而失败。棘手。

答案 1 :(得分:1)

我相信你应该使用IsolatedStorageFileStream

using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{            
     using (var isfs = new IsolatedStorageFileStream(selected.Path, FileMode.Open, isf))
     {                        
          this.media.SetSource(isfs);              
     }                    
}

另请注意,您无需调用.Close().Dispose()方法,因为它们在using语句中已被处理。