The following information is for the EMANT300, EMANT380

Exercise 12 – File IO

Objective

  • File IO

Instead of writing to the console, a StreamWriter class is available for those who wish to write to file instead of displaying the result on the console.

  1. Open the Visual Basic solution VB_2010_Solution.sln.

  2. Set the LightFile project as the startup project.

  3. View the project code by opening the project's Module1.vb

  4. If you are using the EMANT380 Bluetooth DAQ, change the parameter to False and COM5 to the COM port you are using, See exercise 1 step 4.

    DAQ.Open(False,"COM5")

  5. Press Ctrl+F5 to Start without Debugging to run the program. 10 Light Intensity measurements in Lux will be displayed and written to a text file named TestFile.txt at the rate of 1 measurement per second.

  6. Press any key to return to the development environment.

  7. You can find TestFile.txt in the Solution\LightFile\bin\Release folder if you pressed Ctrl+F5 to Start without Debugging. Alternatively you can find TestFile.txt in the Solution\LightFile\bin\Debug folder if you pressed F5 to Start with Debugging.

Program 12.1 Log to File

Imports Emant  
Imports System.IO  
Module Module1  
    Sub Main()  
        Dim volt, lux As Double  
        Dim i As Integer  
        Dim DAQ As Emant300 = New Emant300  
        Dim sw As StreamWriter = New StreamWriter("TestFile.txt")  
        DAQ.Open(True, "COM5")  
        For i = 0 To 9  
            volt = DAQ.ReadAnalog(Emant300.AIN.AIN0, Emant300.AIN.COM)  
            lux = 1333 * volt  
            Console.WriteLine(lux)  
            sw.WriteLine(lux)  
            DAQ.Delay(1000)  
        Next  
        DAQ.Close()  
        sw.Close()  
    End Sub  
End Module

If you are writing this program from scratch, in order to use the Emant300 class, the class library Emant300.dll must be added to the references folder. See exercise 5.

StreamWriter Class

Imports System.IO

Allows unqualified reference to the StreamWriter objects

Dim sw As StreamWriter = New StreamWriter("TestFile.txt")

Create a StreamWriter object called sw that writes to a text file called TestFile.txt

sw.WriteLine(lux)

StreamWriter method that writes the lux value to the file

sw.Close()

Close the StreamWriter object called sw

Information on the StreamWriter Class can be found at the Microsoft website. Search using the keywords StreamWriter Class

End of Exercise 12