0

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

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Nick
  • 99
  • 7
  • 1
    The answer to your problem is the [Using Statement](https://msdn.microsoft.com/en-us/library/htd05whh.aspx) – Steve Jul 05 '15 at 20:28

2 Answers2

0

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()
Joe Raio
  • 1,795
  • 1
  • 12
  • 17
0

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, ...).

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519