防止在 WPF 应用程序中打开文件的多个副本

发布于 2024-10-29 13:09:36 字数 546 浏览 0 评论 0原文

我有一个 WPF 应用程序,可以打开和编辑 XML 文件。目前,该应用程序可以多次启动,并且多个实例可以打开同一文件。我需要锁定文件,这样当一个文件打开时,它不会让应用程序的另一个实例打开该文件。我尝试在打开文件时使用 FileShare.None 属性以及 FileStream.Lock(),但由于某种原因,这些无法阻止应用程序的单独实例打开它。

编辑:相关代码

try
{
    FileStream iStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    iStream.Lock(0, iStream.Length);

    // DO STUFF WITH FILE HERE
}
catch (System.IO.IOException ioException)
{
    // Raise exception to higher level, where application will terminate. 
    throw (ioException);
}

I have a WPF app, which opens and edits XML files. Currently, the app can be launched multiple times, and several instances can have the same file open. I need to lock the files such that, when one is open, it won't let another instance of the app open the file. I have tried using the FileShare.None attribute when opening the file, as well as FileStream.Lock(), but for some reason, these fail to prevent a separate instance of the app from opening it.

EDIT: Relevant code

try
{
    FileStream iStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    iStream.Lock(0, iStream.Length);

    // DO STUFF WITH FILE HERE
}
catch (System.IO.IOException ioException)
{
    // Raise exception to higher level, where application will terminate. 
    throw (ioException);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

英雄似剑 2024-11-05 13:09:36

从开始编辑到关闭,您需要始终保持文件打开状态(假设您的应用程序的每个实例都有单独的进程)。

您的代码看起来像是在方法内打开文件,并且可能在此方法内通过使用短文件操作建议的“使用”来关闭它,或者只是让 GC 关闭它。结果,您锁定文件一段时间,但很快就会释放它,以便其他实例能够再次打开它。

请注意,如果您的应用程序实现某种单实例方法,则这种锁定可能还不够,因为所有打开操作都将从同一进程执行。

You need to keep file open all the time you are "editing" it from the moment you start editing till closing (assuming you have separate processes for each instance of your app).

Your code looks like you are opening file inside on method and likely close it inside this method either by using "using" as recommended for short file operations or just letting GC to close it. As result you lock file for some time, but release it soon enough for other instances to be able to open it again.

Note that if your application implements some sort of single instance approach this locking may not be enough as all of the open operations will be executed from the same process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文