Creating/editing textfile through VB.NET

人走茶凉 提交于 2019-12-23 08:12:14

问题


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


来源:https://stackoverflow.com/questions/1332260/creating-editing-textfile-through-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!