1

I'm working on a gradebook program assignment for a class; the details aren't so important, except to know that I need to be able to save a file and recall it later. I know how to serialize, deserialize, etc, and everything's good there. But the problem comes when I try to save. I'm a bit new to the whole saving data scene, and I don't exactly know the techniques, but what I have seems like it should work - except that every time I try it, I get an error.

private static void Save (IList<GradebookEntry> gradebook) {
        Console.WriteLine ("Saving changes. Please wait...");
        using (IsolatedStorageFile stored = IsolatedStorageFile.GetStore (IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null)) {
            try {
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream ("Temp.utc", FileMode.Create, stored)) {
                    BinaryFormatter bform = new BinaryFormatter ();
                    bform.Serialize (isoStream, gradebook);
                    string[] s = stored.GetDirectoryNames ();
                    stored.DeleteFile ("Gradebook.utc");
                    stored.MoveFile ("Temp.utc", "Gradebook.utc"); // #!!
                }
                Console.WriteLine ("Changes saved.");
            }
            catch (Exception ex) {
                Console.WriteLine ("Saving failed. Reason: {0}", ex.Message);
            }
            finally {
                if (stored.FileExists("Temp.utc")) {
                    stored.DeleteFile ("Temp.utc");
                }
            }
        }
    }

The marked line, where I try to move the file, is where I have problems. Everything else works fine, but when I reach that line, it throws an IsolatedStorageException with the message "Operation not permitted". I've looked all over, I've studied MSDN, I've searched all the places I can, but I can't figure out what the problem is. It's probably just something I overlooked, but I'm tearing my hair out here and I could use a bit of help. Thanks.

4

1 回答 1

0

为了扩展执政官的评论,移动操作失败,因为它在 using 块内。如下更改代码可以解决问题。

using (IsolatedStorageFileStream isoStream = 
            new IsolatedStorageFileStream("Temp.utc", FileMode.Create, stored)) 
{
    BinaryFormatter bform = new BinaryFormatter();
    bform.Serialize(isoStream, gradebook);
}
stored.DeleteFile("Gradebook.utc");
stored.MoveFile("Temp.utc", "Gradebook.utc");

失败的原因Temp.utcusing 块打开了文件,并且无法移动打开的文件。一旦执行离开 using 块,Dispose就会调用该方法isoStream,导致它关闭打开的文件。

于 2015-10-02T16:38:05.533 回答