farad100
farad100

Reputation: 1

Writing to two text files using vb.net

I cannot write this value into two separate text files. It only writes to one.

Public Class frmIceCream
Dim tw As System.IO.TextWriter

Then in the form load I have the following:

tw = New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\sundae.txt", True)
tw.WriteLine("5")

tw = New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\banana.txt", True)
tw.WriteLine("5")

Upvotes: 0

Views: 2353

Answers (3)

JDB
JDB

Reputation: 25875

The issue you are most likely dealing with is that the first text file is empty.

Writing to the harddrive is expensive, so the TextWriter uses a buffer that holds some amount of text and then writes it all at once. Try using tw.Flush() to write whatever is left in the buffer then use tw.Close() to free the resource.

This should work:

tw = New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\sundae.txt", True)
tw.WriteLine("5")
tw.Flush()
tw.Close()

tw = New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\banana.txt", True)
tw.WriteLine("5")
tw.Flush()
tw.Close()

Upvotes: 0

Victor Zakharov
Victor Zakharov

Reputation: 26454

For the shortest possible code snippet, you can use File.WriteAllText:

File.WriteAllText("C:\Users\F\Documents\Temp junk\sundae.txt", "5")
File.WriteAllText("C:\Users\F\Documents\Temp junk\banana.txt", "5")

If you want to keep using your approach, it is generally preferable to keep your file open for as short as possible. I would wrap your file operations into Using blocks, this way StreamWriter is disposed (and closed) automatically:

Using tw As New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\sundae.txt", True)
  tw.WriteLine("5")
End Using
Using tw As New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\banana.txt", True)
  tw.WriteLine("5")
End Using

Notice here that even though you are technically using different tw objects, you can keep the same name, if it makes code more readable for you.

Upvotes: 2

TimG
TimG

Reputation: 602

You can't reuse the variable until you close the other file. It is probably easier to have two files open. Try this:

Dim tw1 as System.IO.TextWriter, tw2 as System.IO.TextWriter

tw1 = New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\sundae.txt", True) 
tw1.WriteLine("5")
tw2 = New System.IO.StreamWriter("C:\Users\F\Documents\Temp junk\banana.txt", True)
tw2.WriteLine("5")

Upvotes: 2

Related Questions