Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Ok, i have two programs one program writes to a text file on a consistent basis, while the second program is opening this text file on a consistent basis for reading..

 

Sometimes the programs are accessing the file at the same time and the user keeps getting this error : this process cannot access the file because its already in use..

 

Is there any class, in system.io that i can use to modify the settings of this text file so both programs can access it at the same time?

 

Any help would be appreciated!

  • Leaders
Posted

This doesn't really have anything to do with the settings of the text file, per se, so much as how one program or another is using the text file. Normally, when a program opens a file, the file is locked so that no other program can open the file.

 

There is a straightforward way around this, but it requires that you access the file via a FileStream (i.e. you can't do this with methods such as File.ReadAllLines).

var fileStream = System.IO.File.Open(
   "MyFile.txt", 
   System.IO.FileMode.Open,  
   System.IO.FileAccess.ReadWrite, 
   [color="Red"]System.IO.[i]FileShare[/i].ReadWrite);[/color]

The FileShare value specifies how the program is willing to share the file. You can allow other programs to read the file, or to write to the file, or both.

 

But before you slap file-access-sharing into your programs, first consider why .NET (or any self-respecting API) would default to locking a file. If one program is writing while the other is reading things can go terribly wrong. Things get sketchy when the file is being modified under your feet as you read it. The only way I would feel safe doing this is if the two programs were working together and communiticating what was going on to eachother, but if the two programs are communiticating to eachother they should be able to skip the file and send the info in question directly to eachother. Beyond that, when you share the file access, you can't pick and choose who else can access the file. It won't be limited to your other program, and that sounds a little sketchy to me, too.

[sIGPIC]e[/sIGPIC]
Posted

Thanks for the info.. I agree to it can get complicated two programs accessing it at the same time.. At the time it's what the user wanted, but he has since changed his mind..

 

You reply hasn't been in vain tho.. I learned something new :)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...