Creating/editing textfile through VB.NET

2019-06-18 03:43发布

问题:

How do I code the algorithm below in 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;
}

回答1:

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

If you set the second parameter to True in the System.IO.StreamWriter's constructor it will append to a file if it already exists, or create a new one if it doesn't.



回答2:

This can be achieved in a single line too:

System.IO.File.AppendAllText(filePath, "Hello World" & vbCrLf)

It will create the file if missing, append the text and close it again.

See MSDN, File.AppendAllText Method.



回答3:

It's best to use a component that does this type of logging out of the box. The Logging Application Block from Enterprise Library for example. That way, you get flexibility, scalability and don't have contention with your log file.

To answer your question specifically (sorry, I don't know VB, but the translation should be simple enough) ...

void Main()
{
    using( var fs = File.Open( @"c:\textfile.txt", FileMode.Append ) )
    {
        using( var sw = new StreamWriter( fs ) )
        {
          sw.WriteLine( "New Line" );
          sw.Close();
        }

        fs.Close();
    }
}