获取IsolatedStorageException:IsolatedStorageFileStream上不允许操作

Amy*_* Li 9 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();
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:异常被抛出: 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)
Run Code Online (Sandbox Code Playgroud)

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

Kev*_*sse 8

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

var isfs = isf.OpenFile(selected.Path, FileMode.Open, FileShare.Read)
Run Code Online (Sandbox Code Playgroud)

虽然我不明白为什么会发生,因为你明确关闭了文件.

编辑:好的,用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);
}
Run Code Online (Sandbox Code Playgroud)

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