File Access Conflict

  • Thread starter Thread starter OpticTygre
  • Start date Start date
O

OpticTygre

Hi folks,

I have a function:

Public Function CreateDelta(ByVal FileName1 As String, ByVal FileName2 As
String) As String
If Not File.Exists(FileName2) Then
File.Create(FileName2)
End If

Dim sr As StreamReader = New StreamReader(FileName1)
Dim sr2 As StreamReader = New StreamReader(FileName2)
Dim String1 As String
Dim String2 As String
Dim Output As String

Do While True
Try
String1 = sr.ReadLine
String2 = sr2.ReadLine

If String1 <> String2 Then Output = Output & String1 &
vbNewLine

Catch ex As Exception
Exit Do
End Try

Application.DoEvents()
Loop

sr.Close()
sr2.Close()

CreateDelta = Output
End Function

The issue I'm having is right at the top. If FileName2 doesn't exist, it
creates a blank FileName2. Then, it errors out when I try and open the
StreamReader for FileName2, because it says the file is being used by
another process. How can I preven this behavior? Thanks for any replies.

-J
 
Maybe...

If Not File.Exists(FileName2) Then
Dim sw2 As StreamWriter = File.CreateText(FileName2)
sw2.Close ' <--- important perhaps
End If

Dim sr As StreamReader = File.OpenText(FileName1) <-- same a new
streamreader
Dim sr2 As StreamReader = File.OpenText(FileName2) <-- same a new
streamreader

PS: I would look at using a Stringbuilder where you are concatenating the
strings...

Greg
 
Could you use the Filestream class:

dim fs as filestream
if file.filename2.exists then
fs = New FileStream(filename2, FileMode.CreateNew)
else
fs = New System.IO.FileStream(filename2, FileMode.Open)
end if
 
Back
Top