(VB.NET, .NET 3.5)
I wrote the following function to read some text from txt file. It was working fine but now it’s not. It keeps giving me this error message
‘IOException was unhandled’ and
‘ The process cannot access the file ‘F:\kh_matt\ch1.txt’ because it is being used by another process.’
The ch1.txt is not even opened or being used by any program at all. I tried to move ch1.txt to another location (Drive D) still I got the same message error but just different location it says The process cannot access the file ‘D:\ch1.txt’ because it is being used by another process.’
Here’s my code block :
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim reader As StreamReader Dim filelocation As String filelocation = 'F:\kh_matt\ch1.txt' Dim chid As Integer chid = 1 If System.IO.File.Exists(filelocation) = True Then reader = New StreamReader(New FileStream(filelocation, FileMode.Open)) Else MsgBox(filelocation, MsgBoxStyle.OkOnly) End If Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation)) Dim vArray() As String = MyStream.ReadToEnd.Split(CChar('$')) MyStream.Close() Dim count As Integer For d As Integer = 0 To vArray.Length - 1 Step 1 If d = vArray.Length - 1 Then Exit For End If InsertKh(chid, d + 1, vArray(d)) count = d + 1 Next MsgBox('Done Inserting') End Sub
It always points to this code :
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Where I debug and press the respective button. Can anyone point out what the problem is ? Thanks
It seems you open the file twice, which is probably what’s causing your error:
Are you sure that’s what you intend to do? It looks like you can remove
MyStreamand usereaderinstead. Also, you don’t have to usePath.Combine, sincefilelocationis not relative.