7

How do I code the algorithm below in VB.NET?

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;
}

4 Answers 4

12
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.

Sign up to request clarification or add additional context in comments.

Comments

8

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.

Comments

2

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();
    }
}

Comments

0
 For editing :
 Try
     Dim thefile As String = "C:\con_ip.txt" 'Put your path
     Dim lines() As String = System.IO.File.ReadAllLines("C:\con_ip.txt")
     lines(Put which line to edit) = "Put the Value to edit "
     System.IO.File.WriteAllLines(thefile, lines)
 Catch ex As Exception

 End Try

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.