This code works great on windows:
https://stackoverflow.com/a/11318745/637142
I am creating an application targeting netcoreapp2.1
. When I run that code under Linux I am able to delete the file. If my application is running I want to prevent deletions of a specific file. How can I do that?
Further explanation
I have this code:
// this code only runs on Linux
var fs = File.Open(@"/tmp/foo.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
fs.Lock(0, 0);
// Wait for 1 minute
for (var i = 0; i < 60; i++)
{
Console.WriteLine("This is a test.");
System.Threading.Thread.Sleep(1000);
fs.Lock(0, 0); // this is not needed I just have it
}
// Do your work here
fs.Close();
When I run that code I am able to execute the command "rm /tmp/foo.txt" and that command successfully deletes the file. Note when I login to my Linux computer I am root.
What am I trying to solve:
I try to make my logic of my Windows application similar to the logic of my Linux application. In this case they differ.
If I place a lock like on the first example I am able to have something like:
bool isProcessExecuting;
try
{
System.IO.File.Delete(someFileContainingALock);
isProcessExecuting = false;
}
catch
{
isProcessExecuting = true;
}
if (isProcessExecuting)
{
// prevent starting another instance of the same program
return;
}
// else continue execution
For example this code enables me to prevent running multiple instances of the same application. I know there are alternative ways of doing the same thing. It will be nice if I can use the same code on Windows and Linux. And in this case my linux code will have to be different