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.
To expand on archon's comment, the move operation fails because it's inside the using block. Changing the code as follows fixes the problem.
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");
The reason why it fails is that the using block has the file Temp.utc
open, and an open file can't be moved. Once execution leaves the using block, the Dispose
method is called on isoStream
which causes it to close the open file.