How do i get this to write to a txt file instead of message box pleaseWr

    Function ReceiveSerialData() As String
        ' Receive strings from a serial port. 
        Dim returnStr As String = ""

        Dim com1 As IO.Ports.SerialPort = Nothing
        Try
            com1 = My.Computer.Ports.OpenSerialPort("COM3")
            com1.ReadTimeout = 10000
            Do
                Dim Incoming As String = com1.ReadLine()
                If Incoming Is Nothing Then
                    Exit Do
                Else
                    returnStr &= Incoming & vbCrLf
                    MessageBox.Show(returnStr)
                End If
            Loop
        Catch ex As TimeoutException
            MessageBox.Show("Error: Serial Port read timed out.")
        Finally
            If com1 IsNot Nothing Then com1.Close()
        End Try

        Return returnStr
    End Function

That doesnt really explain how to

No kidding. Microsoft would explain a beach by describing (in great detail) every grain of sand and every possible activity that can be done on that beach. Simple examples are often lacking.

Declare a StreamWriter as

Dim sw As New System.IO.StreamWriter("d:\temp\myfile.txt", False)

Set the second parameter to True to append to a file instead of overwriting. Replace

MessageBox.Show(returnStr)

with

sw.WriteLine(returnStr)

or

sw.Write(returnStr)

depending if you want to add a vbCrLf to the output. Don't forget to do

sw.Close()

when done. You've only shown the code in the event handler and it would be inefficient to do the open/close repeatedly in the handler. You might want to do the open and close at a higher level.

Put this on top of your class or form1:
Imports System.IO
Put this into your function instead of the msgbox:

Using writer As StreamWriter = New StreamWriter("C:\append.txt", True)
            writer.WriteLine("First line appended; 1")
        End Using

This creates a new file if the file doesn't exist

@ Jim
Sorry we just posted almost at the same moment.
Cheers

As Archie Bunker would say, like two sheeps that pass in the night ;-P

That doesn't really explain how to

No offence but did you even scroll down and check out the examples? From there you would have seen how to write and read to and from text files.

It's great that you have been given examples but MSDN is your core documentation and if you are serious about learning to program I highly suggest you get familiar with it. It won't answer all of your questions but it will help with most.

Again, not trying to be rude just trying to point you in the right direction.

 My.Computer.FileSystem.WriteAllText('your text file name here', 'the return that you display as message here', True)

That should also work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.