我开发了一个 C# 表单应用程序,可作为公司服务器上的 exe 文件使用,可供所有计算机访问。当它已经在任何计算机上运行时,我需要阻止某人运行它。
我看过SO中的其他解决方案,但只有在同一台计算机运行exe两次时它们才能正常工作。
在服务器上有一个用户可写的文件。当应用程序启动时,打开该文件进行写入,并在静态字段中保留对 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();
}
}
基于