vb.net VB 写入前清除文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29973142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:05:13  来源:igfitidea点击:

VB Clear text file before writing

vb.netvisual-studiotextsave

提问by Mathijs

On the click of a button I want to write my textbox.text into a text file. I got this code working, but I want to clear the textfile before writing and not just add text.

单击按钮后,我想将 textbox.text 写入文本文件。我让这段代码正常工作,但我想在编写之前清除文本文件,而不仅仅是添加文本。

    Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem. _
    OpenTextFileWriter(mfileName, True)
    file.WriteLine(TextBox1.Text)
    file.Close()

Any help appreciated.

任何帮助表示赞赏。

回答by Alex K.

Simply

简单地

My.Computer.FileSystem.OpenTextFileWriter(mfileName, False)

Where Falsedisables appending and activates overwriting.

其中False禁用附加并激活覆盖。

回答by Steve

Just use File.WriteAllText

只需使用File.WriteAllText

As explained by MSDN

正如 MSDN 所解释的

Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

创建一个新文件,将内容写入文件,然后关闭文件。如果目标文件已经存在,它会被覆盖。

Your code becomes just one line

你的代码变成了一行

File.WriteAllText(mfileName, TextBox1.Text)