How to lock a text file?

  • Thread starter Thread starter Peter
  • Start date Start date
P

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
 
Peter said:
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?
 
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
 
Peter said:
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.
 
I see, I should set the FileAccess and FileShare parameters for the
FileStream object.

Thank you, Chris

Peter
 
Back
Top