473,574 Members | 2,573 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Two diffrent Process tries to open file at the same time.....

Hi All,
I am working on the situation where 2 different
Process/Application(.ne t) 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
ABCL

May 21 '06 #1
1 19876
Hello ABCL ,
The following words are copied from "c# Cook Book, 2nd edition"-"Recipe
12.22. Locking Subsections of a File",I think its useful:
/*************** *copied******** *************** **/
Problem
You need to read or write data from or to a section of a file, and you
want to make sure that no other processes or threads can access,
modify, or delete the file until you have finished with it.

Solution
Locking out other processes from accessing your file while you are
using it is accomplished through the Lock method of the FileStream
class. The following code creates a file from the fileName parameter
and writes two lines to it. The entire file is then locked using the
Lock method. While the file is locked, the code goes off and does some
other processing; when this code returns, the file is closed, thereby
unlocking it:

public static void CreateLockedFil e(string fileName)
{
using (FileStream fileStream = new FileStream(file Name,
FileMode.Create ,
FileAccess.Read Write,
FileShare.ReadW rite))

{
using (StreamWriter streamWriter = new
StreamWriter(fi leStream))
{
streamWriter.Wr iteLine("The First Line");
streamWriter.Wr iteLine("The Second Line");
streamWriter.Fl ush( );

// Lock all of the file.
fileStream.Lock (0, fileStream.Leng th);

// Do some lengthy processing here...
Thread.Sleep(10 00);

// Make sure we unlock the file.
// If a process terminates with part of a file locked or
closes a file
// that has outstanding locks, the behavior is undefined
which is MS
// speak for bad things....
fileStream.Unlo ck(0, fileStream.Leng th);

streamWriter.Wr iteLine("The Third Line");
}
}
}

Discussion
If a file is opened within your application and the FileShare parameter
of the FileStream.Open call is set to FileShare.ReadW rite or
FileShare.Write , other code in your application can view or alter the
contents of the file while you are using it. To handle file access with
more granularity, use the Lock method of the FileStream object to
prevent other code from overwriting all or a portion of your file. Once
you are done with the locked portion of your file, you can call the
Unlock method on the FileStream object to allow other code in your
application to write data to that portion of the file.

To lock an entire file, use the following syntax:

fileStream.Lock (0, fileStream.Leng th);

To lock a portion of a file, use the following syntax:

fileStream.Lock (4, fileStream.Leng th - 4);

This line of code locks the entire file except for the first four
characters. Note that you can lock an entire file and still open it
multiple times, as well as write to it.

If another thread is accessing this file, it is possible to see an
IOException thrown during the call to either the Write, Flush, or Close
methods. For example, the following code is prone to such an exception:

public static void CreateLockedFil e(string fileName)
{

using (FileStream fileStream = new FileStream(file Name,
FileMode.Create ,
FileAccess.Read Write,
FileShare.ReadW rite))

{
using (StreamWriter streamWriter = new
StreamWriter(fi leStream))
{
streamWriter.Wr iteLine("The First Line");
streamWriter.Wr iteLine("The Second Line");
streamWriter.Fl ush( );

// Lock all of the file.
fileStream.Lock (0, fileStream.Leng th);

using (StreamWriter streamWriter2 = new StreamWriter(
new FileStream(file Name,
FileMode.Open,
FileAccess.Writ e,
FileShare.ReadW rite)))
{
streamWriter2.W rite("foo ");
try
{
streamWriter2.C lose( ); // --> Exception occurs
here!
}
catch
{
Console.WriteLi ne(
"The streamWriter2.C lose call generated an
exception.");
}
streamWriter.Wr iteLine("The Third Line");
}
}
}
}

This code produces the following output:

The streamWriter2.C lose call generated an exception.

Even though streamWriter2, the second StreamWriter object, writes to a
locked file, it is when the streamWriter2.C lose method is executed that
the IOException is thrown.

If the code for this recipe were rewritten as follows:

public static void CreateLockedFil e(string fileName)
{
using (FileStream fileStream = new FileStream(file Name,
FileMode.Create ,

FileAccess.Read Write,
FileShare.ReadW rite))

{
using (StreamWriter streamWriter = new
StreamWriter(fi leStream))
{
streamWriter.Wr iteLine("The First Line");
streamWriter.Wr iteLine("The Second Line");
streamWriter.Fl ush( );

// Lock all of the file.
fileStream.Lock (0, fileStream.Leng th);

// Try to access the locked file...
using (StreamWriter streamWriter2 = new StreamWriter(
new FileStream(file Name,
FileMode.Open,
FileAccess.Writ e,
FileShare.ReadW rite)))
{
streamWriter2.W rite("foo");
fileStream.Unlo ck(0, fileStream.Leng th);
streamWriter2.F lush( );
}
}
}
}

no exception is thrown. This is due to the fact that the code closed
the FileStream object that initially locked the entire file. This
action also freed all of the locks on the file that this FileStream
object was holding onto. Since the streamWriter2. Write("Foo") method
had written Foo to the stream's buffer (but had not flushed it), the
string Foo was still waiting to be flushed and written to the actual
file. Keep this situation in mind when interleaving the opening,
locking, and closing of streams. Mistakes in code sometimes manifest
themselves a while after they are written. This leads to some bugs that
are more difficult to track down, so tread carefully when using file
locking.

May 21 '06 #2

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

Similar topics

9
715
by: Paul | last post by:
Hi, VB.NET is saying the file I am creating is in use by another process and won't complete its task of moving the file to the specified destination folder. Here is my code (the main bit anyway).... Private Sub LogChange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs) If e.ChangeType = WatcherChangeTypes.Created Then
2
2226
by: PMac | last post by:
I'm trying to execute a stand-alone console application from an aspx page when a use clicks a button on that page. On the aspx page is the following lines of pertinent code: private void btnStartApp(object sender, System.EventArgs e) { Process procID; string procName; ProcessStartInfo psi = new ProcessStartInfo();
5
4587
by: Dino Buljubasic | last post by:
My application can allow a user to open a file for viewing by fetching file data from database, creating the file in a temp directory and starting appropriate process (i.e. Adobe or any other depending of file type) to open the file. when I close my application, it is suppose to clean all files it created in temp directory. I do this by...
4
9608
by: Paddy | last post by:
We have a recurring problem where a (long-running) service throws an exception while trying to access a file. The problem is that this is very rare (happens once every week and without warning) but does happen time to time. We are trying ways to find which other process is holding on to the file or even if any other thread from our process is...
13
11120
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...
8
4978
by: Tom Wright | last post by:
I'm writing a program which reads a series of data files as they are dumped into a directory by another process. At the moment, it gets sporadic bugs when it tries to read files which are only partially written. I'm looking for a function which will tell me if a file is opened in write-mode by another process - if it is, my program will...
8
3208
by: Lonifasiko | last post by:
Hi, Using Process class I asynchronously launch an executable (black box executable) file from my Windows application. I mean asynchronously because I've got an EventHandler for "Exited" event. Therefore, when process finishes, "Exited" event is raised. This executable writes a long file for over 1-5 minutes, and I, from my application...
3
1452
by: Rudemusik | last post by:
Hello all! Working in vb.net, with VS 2003. I have 2 projects in a solution. Pretty much a client server setup. Project A controls when a message box open up on Project B. Click a button on A, and the message box will open on B. and the message box in this case is a small form. Pretty much all the control I have is the forms. Depending...
0
5085
by: mix01 | last post by:
Hi, I am trying to get some VBA code working, but am preplex as to why it does not work. I would really appreciate any level of help. Many thanks, Mix01 Version of the program
0
7738
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8077
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. ...
0
8113
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...
0
6476
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...
1
5634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3765
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2253
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
1
1358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1076
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...

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.