views:

801

answers:

4

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;
}
A: 
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.

Kirtan
+2  A: 

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

Shoban
+1 I agree, give the guy a fishing reel instead of a fish.
Cyril Gupta
A: 

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();
    }
}
JP Alioto
A: 

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.

Jakob Gade