通过VB.NET创建/编辑文本文件

sef*_*sef 7 vb.net text-files

我如何在VB.NET中编写以下算法?

Procedure logfile()
{
    if "C:\textfile.txt"=exist then
        open the textfile;
    else
        create the textfile;
    end if  
    go to the end of the textfile;
    write new line in the textfile;
    save;
    close;
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*tan 12

Dim FILE_NAME As String = "C:\textfile.txt"
Dim i As Integer
Dim aryText(4) As String

aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "Another"
aryText(3) = "Little"
aryText(4) = "One"

Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)

For i = 0 To 4
    objWriter.WriteLine(aryText(i))
Next

objWriter.Close()
MsgBox("Text Appended to the File")
Run Code Online (Sandbox Code Playgroud)

如果TrueSystem.IO.StreamWriter构造函数中设置第二个参数,它将附加到文件(如果已存在),或者如果不存在则创建新文件.


Jak*_*ade 8

这也可以在一行中实现:

System.IO.File.AppendAllText(filePath, "Hello World" & vbCrLf)
Run Code Online (Sandbox Code Playgroud)

如果缺少它将创建文件,附加文本并再次关闭它.

请参阅MSDN,File.AppendAllText方法.