Farmer
Farmer

Reputation: 11003

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

I want to open a txt file and write into it numbers from 1 to 100 and put between every number enter.

Upvotes: 0

Views: 6180

Answers (4)

knslyr
knslyr

Reputation: 640

You could also use the "My.Computer.FileSystem" namespace, like:

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)

Upvotes: 1

Muncey
Muncey

Reputation: 36

One way you could try is to write the numbers into a StringBuilder and then use it's ToString() method to get the resulting text:

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

Upvotes: 2

Chase Florell
Chase Florell

Reputation: 47427

There's a good example over at Home and Learn

 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

Upvotes: 1

John Saunders
John Saunders

Reputation: 161831

See System.IO namespace, especially the System.IO.File class.

Upvotes: 0

Related Questions