2

I'm working with text files. Actually one file, where I have to copy information to it. I'm using streamReader and streamWriter. But I'm having an error whenver I close the file and try to open it again. I can't open it again to start writing from where I stopped, and if I use the same IO writer in any other sub method, I get a run-time error message saying that file is being used. Is there any way that I can close and open the text file separately at anytime?

Dim ioFile As New StreamWriter(filename, False)
'code
iofile.close() 

There is no problem in how many times I read or Write in between , but whenever I close it, can't open it.

Jeremy Bade
  • 511
  • 5
  • 11
l3_08
  • 191
  • 1
  • 4
  • 13
  • 1
    Please post your code. Are you closing the streams properly? – Oded Sep 13 '11 at 18:13
  • You are doing battle with other processes on your machine that want to read the file. And prevent you from re-creating it while they do. Virus scanner, search indexer, those kind of programs. Rename the file first. – Hans Passant Sep 13 '11 at 18:58
  • @Hans Passant The access issue kicks in when I try to access the file from a different sub in the same application. I'm printing many times to the same file. For example, I can't call a sub to use it anywhere because then it say the Path file : c:\desktop\text.txt is being used by another program. I'm stuck , I can only write the program in one sub. – l3_08 Sep 13 '11 at 19:10
  • Your code snippet is quite inadequate. No, you can't open the same file twice. Pass ioFile as an argument to the other sub. – Hans Passant Sep 13 '11 at 19:30

1 Answers1

0

Wrap the streamwriter in a using clause, and set AutoFlush to True:

Using ioFile As New StreamWriter(filename, True)
    ioFile.AutoFlush = True
    'Code
End Using
briddums
  • 1,826
  • 18
  • 31
  • This doesn't work. Since im writing many times one after the other, it cleans the one before and keeps the last. Anyway thanks for trying. – l3_08 Sep 13 '11 at 19:06
  • 1
    It is overwriting because the append parameter is set to false. Change that parameter to true and it will append to the file with each write. – briddums Sep 13 '11 at 19:33