Visual Basic 写入打开的文件 (printLine)

Visual basic write in an opened file (printLine)

所以我想这样做:

Open file "this.txt"
Write a line to this file (replacing anything else written to this file)
[Other stuff, irrelevant to the file]
Write a line to this file (replacing anything else written to this file)
Close the file

我以为这很容易,但我错了。我尝试了很多方法,但都失败了。他们要么不让我在打开的文件中写入,要么打开文件并立即关闭它 (WriteAllText)。

我最终使用了 FileOpen()、PrintLine() 和 FileClose(),它们让我可以在一个打开的文件中写入,但 PrintLine 只写入一个新行,它不会替换文件中的所有内容。有什么帮助吗?无论是打印线还是整个事情

文件在我希望它关闭的最后一刻之前保持打开状态是至关重要的(因为我有另一个程序检查该文件何时不是 open/used)。

如果这是关于 VB.NET,那么您可以使用 File.Open() 模式 = FileMode.Truncate。这会在打开时清除文件。这假定文件存在。

您也可以使用 SetLength() 截断:

Dim f As FileStream
' FileMode.Truncate also works, but the file needs to exist from before
f = File.Open("test.txt", FileMode.OpenOrCreate, FileAccess.Write)
f.SetLength(0) ' truncate to zero size
Dim line As String = "hello2"
Dim w = New StreamWriter(f)
w.WriteLine(line)
w.Flush()
w.Close()
f.Close()

如果这是关于 VB6 的,请查看 this question。一种解决方案是导入并使用执行截断的本机 Windows 函数。

在 VB.Net 中,OpenTextFileWriter 完全满足您的需求 (docs):

Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", False)
file.WriteLine("Here is the first string.")
file.Close()