简体   繁体   中英

Using the same file error

On a button click I have the following code to write what Is in my textboxes.

  Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/Nick/Documents/Dra.txt", False)

    file.WriteLine(NameBasic)
    file.WriteLine(LastBasic)
    file.WriteLine(PhoneBasic)
    file.WriteLine(NameEmer1)

On my form load, I load what is in the notepad from what was written, It is saying It is already being used(the file) which is true, how can I have two different functions(write, and read) manipulating the same file with out this error?

The process cannot access the file 'C:\Users\Nick\Documents\Dra.txt' because it is being used by another process.

And here is the code for my onformload

        Dim read As System.IO.StreamReader
    read = My.Computer.FileSystem.OpenTextFileReader("C:/Users/Nick/Documents/Dra.txt")
    lblNameBasic.Text = read.ReadLine

I am sort of stuck on this problem, thank you

You need to close the file when you are done writing to it.

 Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/Nick/Documents/Dra.txt", False)

file.WriteLine(NameBasic)
file.WriteLine(LastBasic)
file.WriteLine(PhoneBasic)
file.WriteLine(NameEmer1)
file.Close()

To answer your question:

how can I have two different functions(write, and read) manipulating the same file with out this error?

If you really want to simultaneously read and write to the same file from two processes, you need to open the file with the FileShare.ReadWrite option . The My.Computer.FileSystem methods don't do that.¹

However, I suspect that you don't really wan't to do that. I suspect that you want to write and, after you are finished writing , you want to read . In that case, just closing the file after using it will suffice. The easiest way to do that is to use the Using statement:

Using file = My.Computer.FileSystem.OpenTextFileWriter(...)
    file.WriteLine(...)
    file.WriteLine(...)
    ...
End Using

This ensures that the file will be closed properly as soon as the Using block is left (either by normal execution or by an exception). In fact, it is good practice to wrap use of every object whose class implements IDisposable (such as StreamWriter ) in a Using statement.


¹ According to the reference source , OpenTextFileWriter creates a New IO.StreamWriter(file, append, encoding) , which in turn creates a new FileStream(..., FileShare.Read, ...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM