2012-07-08 69 views
3

描述:IsolatedStorageFile的MoveFile()方法拋出IsolatedStorageException

下面的代碼是我可以編寫的導致失敗的最簡單的代碼。我也嘗試過:將CreateFile和MoveFile放入不同的使用語句中,將它們放在不同的xaml頁面中,將文件移動到具有新文件名的子目錄中,並將其移動到具有相同文件名的子目錄中。他們都拋出同樣的例外。 CopyFile在所有情況下都引發相同的異常。

問題是 - 什麼令人難以置信的簡單的事情我不佔?

  1. 爲針對Windows Phone 7.1的Windows Phone 7項目打開一個新的Silverlight。
  2. 打開App.xaml.cs.
  3. 的下面幾行代碼粘貼到Application_Launching:

    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) 
    { 
        isf.CreateFile("hello.txt"); 
        isf.MoveFile("hello.txt", "hi.txt"); 
    }
  4. 點擊開始調試,靶向模擬器或設備。

預計:創建名爲「hello.txt」的文件,然後(有效地)將「hello.txt」重命名爲「hi.txt」。
實際:在下面引發異常。

System.IO.IsolatedStorage.IsolatedStorageException was unhandled 
    Message=An error occurred while accessing IsolatedStorage. 
    StackTrace: 
     at System.IO.IsolatedStorage.IsolatedStorageFile.MoveFile(String sourceFileName, String destinationFileName) 
     at PhoneApp4.App.Application_Launching(Object sender, LaunchingEventArgs e) 
     at Microsoft.Phone.Shell.PhoneApplicationService.FireLaunching() 
     at Microsoft.Phone.Execution.NativeEmInterop.FireOnLaunching() 

回答

1

創建文件後應該調用Close

IsolatedStorageFileStream helloFile = store.CreateFile("hello.txt"); 
helloFile.Close(); 
isf.MoveFile("hello.txt", "hi.txt"); 
0

MBen,您的回答不正確。在文件上調用Close並不能解決此錯誤。即使我在MoveFile之前調用「Close」,我也看到了完全相同的錯誤。

編輯好的只是想出了我遇到的問題 - 如果您嘗試在destinationFile已存在時調用MoveFile,它將引發異常。在將sourceFile移到它之前,您必須先刪除destinationFile。

1

我只是有同樣的問題,但解決方案很簡單:
目標文件一定不存在,在移動之前刪除它。確保目標文件在刪除前未在任何地方打開。
源文件不能在任何地方打開。

if (_isolatedStorage.FileExists(targetPath)) 
{ 
    _isolatedStorage.DeleteFile(targetPath); 
} 
_isolatedStorage.MoveFile(sourcePath, targetPath); 
1

完美執行這段代碼

var file = await ApplicationData.Current.LocalFolder.GetFileAsync(oldName); 
    await file.RenameAsync(newName);