Writing to text files without deleting original text

I'm not sure if this is deliberate or if it's a bug, but when i use stream writer to write to a text file it deletes the original text.

Is this supposed to happen or a bug

And is there any way to do this (append text to a file with text already in it)



Answer this question

Writing to text files without deleting original text

  • Michael McCarthy

    For writing text files in the simplest way you could be using the my.computer.filesystem.writealltext method

    http://msdn2.microsoft.com/en-us/library/27t17sxs.aspx

    If you use this then there is argument called append.

    So

    My.computer.filesystem.writealltext (<FileName>, <Contents>, True)

    Will append the contents to the end of filename which is what I assume you looking to do.

    Simple - one line of code.


  • Mach1

     
    ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref8/html/M_System_IO_File_AppendText_1_16219e3a.htm
    Imports System
    Imports System.IO
    
    Public Class Test
      Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim sw As StreamWriter
    
        ' This text is added only once to the file.
        If File.Exists(path) = False Then
          ' Create a file to write to.
          sw = File.CreateText(path)
    
          sw.WriteLine("Hello")
          sw.WriteLine("And")
          sw.WriteLine("Welcome")
          sw.Flush()
          sw.Close()
        End If
    
        ' This text is always added, making the file longer over time
        ' if it is not deleted.
        sw = File.AppendText(path)
        sw.WriteLine("This")
        sw.WriteLine("is Extra")
        sw.WriteLine("Text")
        sw.Flush()
        sw.Close()
    
        ' Open the file to read from.
        Dim sr As StreamReader = File.OpenText(path)
        Dim s As String
        Do While sr.Peek() >= 0
          s = sr.ReadLine()
          Console.WriteLine(s)
        Loop
        sr.Close()
      End Sub
    End Class
    


  • Sheldon Penner

    You need to open the file in append mode!

  • srivastava

    Ah thanks.

    i was just trying out stuff trying to learn the language.

    I didn't know about the File class, i was using this to write to a file:

    Dim x As New StreamWriter("test.txt")

    x.WriteLine("hello")

    x.Close()



  • Sunil_D

    you could also do:

    Code Snippet

    file.txt = file.txt & "write what you want to add here "

    this writes whta is in the text file and adds the "write what you want to add here"



  • Writing to text files without deleting original text