使用vb.net编写两个文本文件

使用vb.net编写两个文本文件,vb.net,Vb.net,我无法将此值写入两个单独的文本文件。它只给一个人写信 Public Class frmIceCream Dim tw As System.IO.TextWriter 然后在表单加载中,我有以下内容: 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\Doc

我无法将此值写入两个单独的文本文件。它只给一个人写信

Public Class frmIceCream
Dim tw As System.IO.TextWriter
然后在表单加载中,我有以下内容:

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")

要获得尽可能短的代码段,可以使用:

如果您想继续使用您的方法,通常最好将文件保持尽可能短的打开状态。我会使用块将您的文件操作包装到
中,这样
StreamWriter
就会自动释放(并关闭):

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

请注意,即使您在技术上使用了不同的
tw
对象,您也可以保留相同的名称,前提是它使代码更易于阅读。

要获得尽可能短的代码片段,您可以使用:

如果您想继续使用您的方法,通常最好将文件保持尽可能短的打开状态。我会使用
块将您的文件操作包装到
中,这样
StreamWriter
就会自动释放(并关闭):

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

请注意,即使您在技术上使用了不同的
tw
对象,您也可以保留相同的名称,前提是它使代码更易于阅读。

在关闭另一个文件之前,您不能重用该变量。打开两个文件可能更容易。试试这个:

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")

在关闭另一个文件之前,无法重用该变量。打开两个文件可能更容易。试试这个:

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")

您最可能处理的问题是第一个文本文件为空

写入硬盘的成本很高,因此TextWriter使用一个缓冲区来保存一定量的文本,然后一次写入所有文本。尝试使用
tw.Flush()
写入缓冲区中剩余的内容,然后使用
tw.Close()
释放资源

这应该起作用:

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()

您最可能处理的问题是第一个文本文件为空

写入硬盘的成本很高,因此TextWriter使用一个缓冲区来保存一定量的文本,然后一次写入所有文本。尝试使用
tw.Flush()
写入缓冲区中剩余的内容,然后使用
tw.Close()
释放资源

这应该起作用:

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()

您看到什么行为表明它只写入一个文件?(即,它正在写入哪个文件?)您看到什么行为表明它只写入一个文件?(即,它正在写入哪个文件?)哇。这个网站太棒了。非常感谢您,我将试一试。:)哇!这个网站太棒了。非常感谢您,我将试一试。:)