Monday, February 21, 2011

creating/editing textfile through vb.net

how do i code in vb.net the algorithm below. tnx!

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;
}
From stackoverflow
  • 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.

  • Giving you the code will be very easy. But here is a nice article which has code as well as some good explanation. : Reading and writing text files with VB.NET

    Cyril Gupta : +1 I agree, give the guy a fishing reel instead of a fish.
  • 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();
        }
    }
    
  • 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.

0 comments:

Post a Comment