在我的应用程序中,用户创建的对象可以序列化并保存为文件。用户还可以打开它们并继续处理它们(就像项目文件一样!)。我注意到我可以在程序打开文件时删除文件,我的意思是我只是将文件反序列化为对象,因此应用程序不再关心文件。
但是,当我的应用程序正在运行并且该文件已加载到程序中时,如何让该文件保持忙碌状态?这是我的Save
和Load
方法:
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;
}
那么我能做什么呢?如何为文件制作假句柄?我的意思是如何做到这一点,所以如果有人试图删除文件,Windows会通过“正在使用文件...”消息来阻止它?