Jump to content

Reading a value from a file (VB)


cali101

Recommended Posts

For a while now, I've been trying to read a value (either 1 or 0) from a .txt file using the StreamReader class, and then pass that value into a variable (integer / string / short byte / etc..).

If the value is 1, then a dialog should show... Here's the code that i'm currently using:-

 

 If File.Exists(".\settings\a.txt") Then
           ioVal = ioRead.ReadToEnd

           If ioVal = 0 Then
               Dialog.Show()
               ioVal = 1
               ioWrite.Write(ioVal)
               ioWrite.Close()
           End If
       Else
           MsgBox("Warning! The file: "".\settings\a.txt"" is missing.")
       End If

 

and in a separate module:-

 

    Public ioVal As Integer
   Public path As String = ".\settings\a.txt"
   Public ioRead As StreamReader = New StreamReader(path)
   Public ioWrite As StreamWriter = New StreamWriter(path)

 

The error I'm getting is a rather ambiguous one: "The type initializer for 'WindowsApplication1.Globals' threw an exception." (that's the module that holds the above code)

 

Looking at the inner exception, it states that: "the process cannot access the file [*file path here*] because it is in use by another process.

Just to point out - this is the only code that accesses that file, and the code runs upon the form-load event.

 

The program halts upon reaching the second line...

 

Additionally, I checked the values using a watch window and the value that the streamreader is getting is the value in the file, however the variable isn't holding what it should be (it always holds '0'), so there must be a problem transferring the value from the file to the variable...

 

 

Any help would be much appreciated,

 

Calimero

Edited by cali101

Share this post


Link to post
Share on other sites

 Public ioVal As Integer
Public path As String = ".\settings\a.txt"
Public ioRead As StreamReader = New StreamReader(path)
Public ioWrite As StreamWriter = New StreamWriter(path)

 

You are trying to open the same file twice. Once to read, then to write. This is your problem.

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...