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

问题描述 投票:0回答:4

如何在 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;
}
vb.net text-files
4个回答
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")

如果您在

True
的构造函数中将第二个参数设置为
System.IO.StreamWriter
,如果文件已存在,它将追加到文件,如果不存在,则创建一个新文件。


8
投票

这也可以通过一行来实现:

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

如果丢失,它将创建文件,追加文本并再次关闭它。

参见 MSDN,File.AppendAllText 方法


2
投票

最好使用可以立即进行此类注销的组件。例如,来自企业库记录应用程序块。这样,您就可以获得灵活性、可扩展性,并且不会与日志文件发生争用。

具体回答你的问题(抱歉,我不懂VB,但是翻译应该够简单了)...

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

0
投票
For editing :
 Try
     Dim thefile As String = "C:\con_ip.txt" 'Put your path
     Dim lines() As String = System.IO.File.ReadAllLines("C:\con_ip.txt")
     lines(4) = q18.Text
     System.IO.File.WriteAllLines(thefile, lines)
 Catch ex As Exception

 End Try
© www.soinside.com 2019 - 2024. All rights reserved.