Home All Groups Group Topic Archive Search About

How to lock a text file?

Author
9 Oct 2006 1:57 AM
Peter
Hi,everybody,

I will edit a text file and another user maybe read it via LAN at any time.
I want to lock the text file(no reading and writing) while I am editting.
Anyone can help me?

Thanks in advance,

Peter

Author
9 Oct 2006 1:25 PM
Chris Dunaway
Peter wrote:
> I will edit a text file and another user maybe read it via LAN at any time.
> I want to lock the text file(no reading and writing) while I am editting.
> Anyone can help me?

It depends on the method you will use to edit the file.  If using
something like a StreamReader or StreamWriter, then specify the
appropriate sharing in the constructor.

Can you give us more information on how you will be editing the file?
Author
10 Oct 2006 12:25 AM
Peter
Hi,  Chris,

Thanks for you reply.
I will write a text file like below:

If System.IO.File.Exists("C:\Test.TXT")  Then
System.IO.File.Delete("C:\Test.TXT")
Dim file1 as new System.IO.StreamWriter("C:\Test.TXT")
file1.Writeline("Here is the first line.")
file1.close

Peter
Author
10 Oct 2006 1:10 PM
Chris Dunaway
Peter wrote:

> If System.IO.File.Exists("C:\Test.TXT")  Then
> System.IO.File.Delete("C:\Test.TXT")
> Dim file1 as new System.IO.StreamWriter("C:\Test.TXT")
> file1.Writeline("Here is the first line.")
> file1.close

I was incorrect in my other post.  The StreamWriter constructor does
not have the sharing argument for the constructor.  Instead, you should
use the FileStream constructor in conjunction with the StreamReader:

Dim fs As New FileStream("filename.ext", FileMode.Open,
FileAccess.ReadWrite, FileShare.Read)

Dim sw As New StreamWriter(fs)

'Work with stream writer here

This file stream opens the file for Read/Write access and allows other
processes to open the file for Read access only.
Author
11 Oct 2006 3:45 AM
Peter
I see, I should set the FileAccess and  FileShare parameters for the
FileStream object.

Thank you, Chris

Peter