Vb.net not closing file after reading from it

streamreader, vb.net, windows

Solution

    Return gateway

That bypasses the sr.Close() call at the bottom. So the file won't be closed. Always favor using the Using statement so it is automatic and can't be forgotten or skipped or bypassed because of an exception:

Public Function EthDefaultGateway() As String
    Using sr As New System.IO.StreamReader(ipconfig)
       '' Rest of your code
    End Using
End Function

Problem

When refreshing my application, I have to read from a text file which has information stored in it. After it is read I make sure I have closed it 'file.close()' the next time I refresh the applicaztion the text file should be generated again and overright the previous one. The problem is that it cant change the file because it is aparantly in use by another process but as soon as I close my application it works fine. Is there anyway to stop the process before refreshing it so it works correctly? The text file is called NetworkInfo.txt. Thanks Chris EDIT Every time I refresh the application I run a batch file that generates a file with all the network info in. (IPConfig/all) I then have a module that reads from it like the following: ``` Public Function EthDefaultGateway() As String Dim sr As New System.IO.StreamReader(ipconfig) Try Dim foundEthernet As Boolean = False Dim gateway As String = "" Do Until sr.EndOfStream Dim line As String = sr.ReadLine() If line.Contains("Ethernet adapter LAN:") OrElse line.Contains("Ethernet adapter Local Area Connection:") Then foundEthernet = True End If If foundEthernet Then If line.Contains("Default Gateway . . . . . . . . . :") Then gateway = line.Substring(line.IndexOf(":") + 1).Trim Exit Do End If End If Loop If gateway = "" Then gateway = "Unknown" End If If gateway = "::" Then gateway = "Unknown" End If Return gateway Catch ex As Exception EthDefaultGateway = "Unknown" End Try sr.Close() sr.Dispose() End Function ``` From this I gather all the bits of information I need. (There probs is a lot better way of doing this but Im only a nooby and I cant find any other ideas on here, the web or from friends.) All of these close the file after readinf from it (sr.close) Some reason though its not closing it. The only other thing It could be is the batch file isnt closing it which I think is very unlikely The problem is that when I change the IP or refresh the form it fails because the batch file cannot over write the network info file. Any suggestions? I was just thinking of a way to kill the process after the refresh but I didnt know if this was a good idea or if it was doable or how to do it tbh.

Original source