text
stringlengths
0
13.4k
Imports System.IO
Dim filename As String = "c:\path\to\file.txt"
File.WriteAllText(filename, "Text to write" & vbCrLf)
Section 16.3: VB StreamWriter
Dim filename As String = "c:\path\to\file.txt"
If System.IO.File.Exists(filename) Then
Dim writer As New System.IO.StreamWriter(filename)
writer.Write("Text to write" & vbCrLf) 'Add a newline
writer.close()
End If
Section 16.4: C# StreamWriter
using System.Text;
using System.IO;
string filename = "c:\path\to\file.txt";
//'using' structure allows for proper disposal of stream.
using (StreamWriter writer = new StreamWriter(filename"))
GoalKicker.com – .NET Framework Notes for Professionals
67
{
writer.WriteLine("Text to Write\n");
}
Section 16.5: C# WriteAllText()
using System.IO;
using System.Text;
string filename = "c:\path\to\file.txt";
File.writeAllText(filename, "Text to write\n");
GoalKicker.com – .NET Framework Notes for Professionals
68
Chapter 17: System.IO
Section 17.1: Reading a text file using StreamReader
string fullOrRelativePath = "testfile.txt";
string fileData;
using (var reader = new StreamReader(fullOrRelativePath))
{
fileData = reader.ReadToEnd();
}
Note that this StreamReader constructor overload does some auto encoding detection, which may or may not
conform to the actual encoding used in the file.
Please note that there are some convenience methods that read all text from file available on the System.IO.File
class, namely File.ReadAllText(path) and File.ReadAllLines(path).
Section 17.2: Serial Ports using System.IO.SerialPorts
Iterating over connected serial ports
using System.IO.Ports;
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i < ports.Length; i++)
{
Console.WriteLine(ports[i]);
}
Instantiating a System.IO.SerialPort object
using System.IO.Ports;
SerialPort port = new SerialPort();
SerialPort port = new SerialPort("COM 1"); ;
SerialPort port = new SerialPort("COM 1", 9600);
NOTE: Those are just three of the seven overloads of the constructor for the SerialPort type.
Reading/Writing data over the SerialPort
The simplest way is to use the SerialPort.Read and SerialPort.Write methods. However you can also retrieve a
System.IO.Stream object which you can use to stream data over the SerialPort. To do this, use
SerialPort.BaseStream.
Reading
int length = port.BytesToRead;
//Note that you can swap out a byte-array for a char-array if you prefer.
byte[] buffer = new byte[length];
port.Read(buffer, 0, length);