如何防止从两台不同的计算机运行exe文件[已关闭]

问题描述 投票:0回答:1

我开发了一个 C# 表单应用程序,可作为公司服务器上的 exe 文件使用,可供所有计算机访问。当它已经在任何计算机上运行时,我需要阻止某人运行它。

我看过SO中的其他解决方案,但只有在同一台计算机运行exe两次时它们才能正常工作。

  1. 防止单个可执行文件的多个进程实例
  2. 如何防止应用程序的两个实例同时执行同一操作?
c# .net windows process locking
1个回答
3
投票

在服务器上有一个用户可写的文件。当应用程序启动时,打开该文件进行写入,并在静态字段中保留对 Stream 的引用。 当应用程序关闭时,关闭 Stream。如果应用程序崩溃或网络中断,操作系统会自动释放该文件。

例如,在您的 Program.cs 中:

private static Stream lockFile;
public static void Main()
{
  try
  {
    try
    {
      lockFile = File.OpenWrite(@"\\server\folder\lock.txt");
    }
    catch (IOException e)
    {
      int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
      if (err == 32)
      {
        MessageBox.Show("App already running on another computer");
        return;
      }
      throw; //You should handle it properly...
    }

    //... run the apps
  }
  finally
  {
    if (lockFile != null)
      lockFile.Dispose();
  }
}

基于

© www.soinside.com 2019 - 2024. All rights reserved.