Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VB.net – How to properly close a text file after reading so it can be opend for writing in the same application

I have a text file that I want to read into a buffer then close it. Later on in the program I want to open the same file to append to it. I get the all too familiar error, that the file can’t be opened because it’s being used by another process, when I try to open it to write to it.

Here is the READ code:

If File.Exists(outfile) Then
    '  Load existing CSV file into csvFIle string to be used a check for duplicates
    rdr = New StreamReader(outfile)
    csvFile = rdr.ReadToEnd
    rdr.Close()
    rdr.Dispose()
    rdr = Nothing '
End If

And this is the code to open for WRITING:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        sw = New StreamWriter(outfile, True) ' append to file
        If newFL Then   ' if the file is new then write the HEADER to the file
            If outbuff > "" Then sw.WriteLine(outbuff)
            outbuff = ""
            newFL = False
        End If

There has got to be a way to completely release the file.
Any help would be greatly appreciated.

Thanks
Nor

>Solution :

Tried to re-create your issue and could not.

    Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    path = IO.Path.Combine(path, "Test.txt")

    Dim line As String
    Using rdr As New IO.StreamReader(path)
        line = rdr.ReadLine
    End Using

    Using wrtr As New IO.StreamWriter(path, True)
        wrtr.WriteLine(line)
    End Using

Makes me suspect that the problem is in the code we aren’t seeing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading