In my application objects created by user can be serialized and saved as file. User can also open them and continue working on them (Just like a project file!). I noticed that I can delete files when they are opened by the program, by that I mean I just deserialize the files into objects so application doesn’t care about the files anymore.
But how can I keep that file busy while my application is running and that file is loaded into program? Here is my Save and Load methods:
public static bool SaveProject(Project proj, string pathAndName)
{
bool success = true;
proj.FileVersion = CurrentFileVersion;
try
{
using (var stream = new FileStream(pathAndName, FileMode.Create, FileAccess.Write, FileShare.None))
{
using(var zipper = new ZlibStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
var formatter = new BinaryFormatter();
formatter.Serialize(zipper, proj);
}
}
}
catch (Exception e)
{
MessageBox.Show("Can not save project!" + Environment.NewLine + "Reason: " + e.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
success = false;
}
return success;
}
public static Project LoadProject(string path)
{
try
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var zipper = new ZlibStream(stream, CompressionMode.Decompress))
{
var formatter = new BinaryFormatter();
var obj = (Project)formatter.Deserialize(zipper);
if (obj.FileVersion != CurrentFileVersion)
{
MessageBox.Show("Can not load project!" + Environment.NewLine + "Reason: File version belongs to an older version of the program." +
Environment.NewLine + "File version: " + obj.FileVersion +
Environment.NewLine + "Current version: " + CurrentFileVersion,
"Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
//throw new InvalidFileVersionException("File version belongs to an older version of the program.");
}
return obj;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Can not load project!" + Environment.NewLine + "Reason: " + ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
return null;
}
So what can I do? How to make a fake handle for the file? I mean how to make it so if someone tries to delete the file, windows prevent it by that ‘file is being used…` message?
Don’t do this. If the user intentionally deletes the file then he’ll have a good reason for it.
If you prevent this by keeping a lock on the file then he’ll simply kill your app and delete the file anyway. All you accomplished is creating an inconvenience, the kind that drives users nuts and gives them a reason to run the uninstaller. If you need to know that the file got deleted while your program is running then you can find out with FileSystemWatcher.