472,353 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 software developers and data experts.

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

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
ABCL

May 21 '06 #1
1 19361
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 CreateLockedFile(string fileName)
{
using (FileStream fileStream = new FileStream(fileName,
FileMode.Create,
FileAccess.ReadWrite,
FileShare.ReadWrite))

{
using (StreamWriter streamWriter = new
StreamWriter(fileStream))
{
streamWriter.WriteLine("The First Line");
streamWriter.WriteLine("The Second Line");
streamWriter.Flush( );

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

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

// 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.Unlock(0, fileStream.Length);

streamWriter.WriteLine("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.ReadWrite 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.Length);

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

fileStream.Lock(4, fileStream.Length - 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 CreateLockedFile(string fileName)
{

using (FileStream fileStream = new FileStream(fileName,
FileMode.Create,
FileAccess.ReadWrite,
FileShare.ReadWrite))

{
using (StreamWriter streamWriter = new
StreamWriter(fileStream))
{
streamWriter.WriteLine("The First Line");
streamWriter.WriteLine("The Second Line");
streamWriter.Flush( );

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

using (StreamWriter streamWriter2 = new StreamWriter(
new FileStream(fileName,
FileMode.Open,
FileAccess.Write,
FileShare.ReadWrite)))
{
streamWriter2.Write("foo ");
try
{
streamWriter2.Close( ); // --> Exception occurs
here!
}
catch
{
Console.WriteLine(
"The streamWriter2.Close call generated an
exception.");
}
streamWriter.WriteLine("The Third Line");
}
}
}
}

This code produces the following output:

The streamWriter2.Close call generated an exception.

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

If the code for this recipe were rewritten as follows:

public static void CreateLockedFile(string fileName)
{
using (FileStream fileStream = new FileStream(fileName,
FileMode.Create,

FileAccess.ReadWrite,
FileShare.ReadWrite))

{
using (StreamWriter streamWriter = new
StreamWriter(fileStream))
{
streamWriter.WriteLine("The First Line");
streamWriter.WriteLine("The Second Line");
streamWriter.Flush( );

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

// Try to access the locked file...
using (StreamWriter streamWriter2 = new StreamWriter(
new FileStream(fileName,
FileMode.Open,
FileAccess.Write,
FileShare.ReadWrite)))
{
streamWriter2.Write("foo");
fileStream.Unlock(0, fileStream.Length);
streamWriter2.Flush( );
}
}
}
}

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
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...
2
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...
5
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...
4
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...
13
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...
8
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...
8
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...
3
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...
0
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...
1
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS...

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.