473,725 Members | 2,264 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 19946
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
2248
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
4596
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 : for each file in temp
4
9612
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 holding on to the file at the specific time that the problem occurs. So, I am trying to...
13
11145
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.
8
5005
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 ignore it for now and come back to it later. This needs to work on linux and windows. Mac OS would...
8
3228
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 must read that file while is being generated.
3
1462
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 what button you press on A, that will react on project B by a certain form opening up. Some forms are...
0
5091
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
8889
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
8752
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
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
8099
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...
1
6702
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
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
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3228
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
2157
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.