2012-05-01 53 views
9

我得到以下的代碼,其目的是要播放從獨立存儲選定的MP3文件上面的異常和錯誤不允許:獲取IsolatedStorageException:操作上IsolatedStorageFileStream

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) 

我已經意識到過,如果我打一首歌不會出現錯誤然後停止播放(用戶界面中有播放和暫停按鈕),然後播放另一首歌曲。它發生在播放一首歌曲時,停止播放,並嘗試再次播放同一首歌曲。

+1

哪條指令觸發錯誤isf.OpenFile?如果是這樣,請確保該文件存在。您可以在打開文件之前調用'isf.FileExists(selected.Path)'來檢查 –

+0

是的,就是這一行。我寫了一個非正式的檢查來控制'isf.FileExists(selected.Path)'的結果,因爲我想也許是這種情況,但它確實並且放入一個實際的if語句並不能解決問題。 –

+0

我想不出爲什麼這段代碼會拋出一個現有文件的異常。你能告訴我們'selected.Path'的價值嗎? –

回答

8

當您播放兩次相同的音樂時會出現該問題,因此可能是文件共享問題。你應該儘量提供OpenFile方法的文件共享參數:

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打開文件而失敗。棘手。

+0

這工作!太多了。:)我不認爲我需要它,要麼因爲我明確關閉文件...但是,這解決了問題。 –

+0

很高興它的工作,但我很無能。我想'media.SetSource'可以防止流被關閉......'media'類型是什麼?如果在不添加FileShare參數的情況下刪除'this.media.SetSource(isfs)'行,是否仍然存在錯誤? –

1

我相信你應該使用IsolatedStorageFileStream

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

另外請注意,你不需要調用.Close().Dispose()方法,因爲它們是在using語句照顧。

+0

我之前嘗試過,仍然得到相同的錯誤。 :( –

相關問題