473,772 Members | 2,349 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File lock

Hi,

I have several processes accessing files from one folder, but only
one process should ever access each file. Once one process has the
file, no other process should be allowed to access it, even after the
first process is finished with it, except in the case where the first
process crashes. In pseudo code..

* Open file with exclusive lock
* Process file - failure will throw exception, skipping 'Remove
file' step below
* Close file and unlock
* Remove file - to clean up, but also to prevent other processes now
accessing the file

...So far I cannot think of a way of doing this, taking into account
pathological cases like the file being accessed between 'Close file
and unlock' and 'Remove file'. The closest I've come however is to use
File.Open(.. FileShare.Delet e), so I can move the 'Remove file' above
the 'Close file and unlock', but then there the problem that someone
could come along and delete the file mid-processing.

Is there a possible solution in .NET? A way to keep the file locked
from other processes, but allow full access in the current, or an
atomic Close and Delete operation. It also needs to work across a
Windows file shared network using the UNC

Thank you,
Kind regards,
Eliott

Jul 18 '07 #1
5 4097
Hi Elliot,

Try experimenting with a lock file and have each process check for the existance of a <Filename>.lo ck which would indicate that even though the file may be accessible, it should not be accessed. Once the file has been removed, remove the lock file as well.

--
Happy coding!
Morten Wennevik [C# MVP]
Jul 18 '07 #2
MRe
Darn it, sorry for the double-post of 'File lock'. Posted through Google and
it didn't show up after a day, so I thought it must have failed

Kind regards,
Eliott
Jul 18 '07 #3
MRe
"Morten Wennevik [C# MVP]" <Mo************ @hotmail.comwro te in message
news:op.tvntr5k 4dj93y5@stone.. .
Hi Elliot,
Thank you for the response Morten Wennevik,
Try experimenting with a lock file and have each process check for the
existance of a <Filename>.lo ck which would indicate that even though the
file may be accessible, it should not be accessed. Once the file has been
removed, remove the lock file as well.
This is almost perfect, except that if the process that gains access to
the file crashes mid-processing, <Filename>.lo ck will not have a chance to
be deleted. Then the file would remain locked until a user deleted the .lock
manually.

I almost get it to work with File.Open(.., FileShare.Delet e) because I can
delete the file while it's still locked and not crashed, plus, if the
program does crash, the OS takes care of the unlocking the file (only
problem is that someone could come along and delete the file
mid-processing).

If it was possible in .NET to create the .lock file so that it
automatically deleted itself when it was closed (like Win32's CreateFile(..,
FILE_FLAG_DELET E_ON_CLOSE); ) then this would work great.
--
Happy coding!
Morten Wennevik [C# MVP]
Thanks again,
Kind regards,
Eliott
Jul 18 '07 #4
On Thu, 19 Jul 2007 00:50:51 +0200, MRe <m.r.e.@.d.u.b. l.i.n...i.ewrot e:
"Morten Wennevik [C# MVP]" <Mo************ @hotmail.comwro te in message
news:op.tvntr5k 4dj93y5@stone.. .
>Hi Elliot,

Thank you for the response Morten Wennevik,
>Try experimenting with a lock file and have each process check for the
existance of a <Filename>.lo ck which would indicate that even though the
file may be accessible, it should not be accessed. Once the file hasbeen
removed, remove the lock file as well.

This is almost perfect, except that if the process that gains accessto
the file crashes mid-processing, <Filename>.lo ck will not have a chance to
be deleted. Then the file would remain locked until a user deleted the.lock
manually.

I almost get it to work with File.Open(.., FileShare.Delet e) becauseI can
delete the file while it's still locked and not crashed, plus, if the
program does crash, the OS takes care of the unlocking the file (only
problem is that someone could come along and delete the file
mid-processing).

If it was possible in .NET to create the .lock file so that it
automatically deleted itself when it was closed (like Win32's CreateFile(..,
FILE_FLAG_DELET E_ON_CLOSE); ) then this would work great.
>--
Happy coding!
Morten Wennevik [C# MVP]

Thanks again,
Kind regards,
Eliott
Well, if you can do it in Win32, you can probably do it in .Net using pinvoke (see www.pinvoke.net)

In case of FILE_FLAG_DELET E_ON_CLOSE I did I quick test and the code below may be what you need. It will create a lock file when a winform loads and the lock file vanishes when the form is closed.

protected override void OnLoad(EventArg s e)
{
IntPtr hFile = Win32.CreateFil e(
"C:\\Test.lock" ,
Win32.GENERIC_R EAD,
0,
IntPtr.Zero,
Win32.CREATE_NE W,
Win32.FILE_FLAG _DELETE_ON_CLOS E,
IntPtr.Zero);
}

class Win32
{
//DesiredAccess
public const UInt32 GENERIC_READ = 0x80000000;
public const UInt32 GENERIC_WRITE = 0x40000000;

//ShareMode
public const UInt32 FILE_SHARE_READ = 0x00000001;
public const UInt32 FILE_SHARE_WRIT E = 0x00000002;

//CreationDisposi tion
public const UInt32 CREATE_NEW = 1;
public const UInt32 CREATE_ALWAYS = 2;
public const UInt32 OPEN_EXISTING = 3;
public const UInt32 OPEN_ALWAYS = 4;
public const UInt32 TRUNCATE_EXISTI NG = 5;

public const UInt32 FILE_FLAG_DELET E_ON_CLOSE = 0x04000000;

[DllImport("Kern el32.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
String lpFileName,
UInt32 dwDesiredAccess ,
UInt32 dwShareMode,
IntPtr lpSecurityAttri butes,
UInt32 dwCreationDispo sition,
UInt32 dwFlagsAndAttri butes,
IntPtr hTemplateFile);
}
--
Happy coding!
Morten Wennevik [C# MVP]
Jul 19 '07 #5
MRe
Hi Morten Wennevik,

Wow, thank you very much for all this code :) looks good. I will give it a
shot

Thank you again,
Kind regards,
Eliott

"Morten Wennevik [C# MVP]" <Mo************ @hotmail.comwro te in message
news:op.tvplo3n qdj93y5@stone.. .
On Thu, 19 Jul 2007 00:50:51 +0200, MRe <m.r.e.@.d.u.b. l.i.n...i.ewrot e:
>[..]
>Try experimenting with a lock file and have each process check for the
existance of a <Filename>.lo ck which would indicate that even though the
file may be accessible, it should not be accessed. Once the file has
been
removed, remove the lock file as well.
[..]
If it was possible in .NET to create the .lock file so that it
automatically deleted itself when it was closed (like Win32's
CreateFile(..,
FILE_FLAG_DELET E_ON_CLOSE); ) then this would work great.
[..]

Well, if you can do it in Win32, you can probably do it in .Net using
pinvoke (see www.pinvoke.net)

In case of FILE_FLAG_DELET E_ON_CLOSE I did I quick test and the code below
may be what you need. It will create a lock file when a winform loads and
the lock file vanishes when the form is closed.

protected override void OnLoad(EventArg s e)
{
IntPtr hFile = Win32.CreateFil e(
"C:\\Test.lock" ,
Win32.GENERIC_R EAD,
0,
IntPtr.Zero,
Win32.CREATE_NE W,
Win32.FILE_FLAG _DELETE_ON_CLOS E,
IntPtr.Zero);
}

class Win32
{
//DesiredAccess
public const UInt32 GENERIC_READ = 0x80000000;
public const UInt32 GENERIC_WRITE = 0x40000000;

//ShareMode
public const UInt32 FILE_SHARE_READ = 0x00000001;
public const UInt32 FILE_SHARE_WRIT E = 0x00000002;

//CreationDisposi tion
public const UInt32 CREATE_NEW = 1;
public const UInt32 CREATE_ALWAYS = 2;
public const UInt32 OPEN_EXISTING = 3;
public const UInt32 OPEN_ALWAYS = 4;
public const UInt32 TRUNCATE_EXISTI NG = 5;

public const UInt32 FILE_FLAG_DELET E_ON_CLOSE = 0x04000000;

[DllImport("Kern el32.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
String lpFileName,
UInt32 dwDesiredAccess ,
UInt32 dwShareMode,
IntPtr lpSecurityAttri butes,
UInt32 dwCreationDispo sition,
UInt32 dwFlagsAndAttri butes,
IntPtr hTemplateFile);
}
--
Happy coding!
Morten Wennevik [C# MVP]
Jul 19 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
7329
by: Pekka Niiranen | last post by:
Hi, I have used the following example from win32 extensions: -----SCRIPT STARTS---- import win32file import win32con import win32security import pywintypes
4
16567
by: KDB | last post by:
Hi, I am trying the following code to get a write lock on a file. #include <unistd.h> #include <iostream.h> #include <fcntl.h> main() { int fd = open("file",O_RDWR);
8
3812
by: Stephen Corey | last post by:
I'm writing an app that basically just appends text to a text file on a Win2K Server. They fill out a form, click a button, and 1 line is appended to the file. Multiple people will run this app at the same time, and all will write to the same file. If I do an immediate flush() on the file after writing the line, is there still a risk that 2 simultaneous writes will collide? If so, what's the best way to handle this type of file write? ...
6
2636
by: martin | last post by:
Hi, I have noticed that every aspx page that I created (and ascx file) has an assosiated resource file aspx.resx. However what I would like to do is have a single global resource file for the site. The resources in this global resource file will possibly change quite often, there I guess this rules out using web.config as every time web.config alters the application is recompiled, also I am not sure of the possible consequences of...
14
3839
by: Gary Nelson | last post by:
Anyone have any idea why this code does not work? FileOpen(1, "c:\JUNK\MYTEST.TXT", OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.Shared) Dim X As Integer For X = 1 To 26 FilePut(1, Chr(X + 64)) Next Lock(1, 5, 10)
4
2260
by: muttu2244 | last post by:
hi all am trying to write some information into the file, which is located in ftp, and this file can be updated by number of people, but if at all i download a file from the ftp to my local machine, update it and then upload it back to ftp, and at the same time if some one else downloads the same file for the modification, then the data will be overwritten. so is there a way in Python script where i can lock the file, so that no one...
1
19955
by: ABCL | last post by:
Hi All, I am working on the situation where 2 different Process/Application(.net) tries to open file at the same time....Or one process is updating the file and another process tries to access it, it throws an exception. How to solave this problem? So second process can wait until first process completes its processing on the file. Thanks in advance
13
11154
by: George | last post by:
Hi, I am re-writing part of my application using C#. This application starts another process which execute a "legacy" program. This legacy program writes to a log file and before it ends, it writes a specific string to the log file. My original program (MKS Toolkit shell program) which keeps running "grep" checking the "exit string" on the "log files". There are no file sharing problem.
2
2626
by: WingSiu | last post by:
I am writing a Logging util for my ASP.NET application. I am facing mulit process problem. I developed a class LogFactory, and have a method called Get_Logger to create a FileLogger, which will write text into a text file. // sample code FileLogger logger = LogFactory.Get_Logger(); logger.Log("Message here");
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6716
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4009
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.