簡體   English   中英

使用VB.NET讀寫文本文件,中間使用單詞

[英]Read and write into a txt file using VB.NET with words in between

我想打開一個txt文件,並寫入到它numbers1 to 100 ,每個號碼之間放enter

您可以嘗試的一種方法是將數字寫入StringBuilder,然后使用其ToString()方法獲取結果文本:

Imports System.IO
Imports System.Text


Public Class NumberWriter
   Private ReadOnly OutputPath as String = _
          Path.Combine(Application.StartupPath, "out.txt")


   Public Sub WriteOut()
       Dim outbuffer as New StringBuilder()

       For i as integer = 1 to 100
          outbuffer.AppendLine(System.Convert.ToString(i))
       Next i

       File.WriteAllText(OutputPath, outbuffer.ToString(), true)
   End Sub

   Public Shared Sub Main()
      Dim writer as New NumberWriter()
      Try
        writer.WriteOut()
      Catch ex as Exception
        Console.WriteLine(ex.Message)
      End Try
   End Sub
End Class

在家學習中有一個很好的例子

 Dim FILE_NAME As String = "C:\test2.txt"

If System.IO.File.Exists(FILE_NAME) = True Then
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
    objWriter.Write(TextBox1.Text)
    objWriter.Close()
    MsgBox("Text written to file")
Else
    MsgBox("File Does Not Exist")
End If

您還可以使用“ My.Computer.FileSystem”命名空間,例如:

Dim str As String = ""
For num As Int16 = 1 To 100
  str += num.ToString & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Working\Output.txt", str, False)

請參見System.IO命名空間 ,尤其是System.IO.File類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM