silastk
silastk

Reputation: 21

C# SerialPort WriteLine Works But Not Write

I am trying to write strings to an internal printer on Com5 with simple write commands. The WriteLine method prints out just fine but the Write will not. Below is the code that I am calling. It is just simple wrapper functions that call the .NET functions.

  public static void Write(string printString)
  {
     //intialize the com port
     SerialPort com5 = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
     com5.Handshake = Handshake.XOnXOff;
     com5.Open();

     //write the text to the printer
     com5.Write(printString);
     Thread.Sleep(100);

     com5.Close();
  }

  public static void WriteLine(string printString)
  {
     //intialize the com port
     SerialPort com5 = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
     com5.Handshake = Handshake.XOnXOff;
     com5.Open();

     //write the text to the printer
     com5.WriteLine(printString);
     Thread.Sleep(100);

     com5.Close();
  }

Upvotes: 2

Views: 3724

Answers (3)

Alicia
Alicia

Reputation: 884

The SerialPort object uses a Stream object for reading and writing at a lower level. It is accessible through the property BaseStream. Maybe if you flush the stream before the Write instruction it will force an update in the stream.

...
//write the text to the printer
com5.Write(printString);
com5.BaseStream.Flush();
Thread.Sleep(100);
...

Alicia.

Upvotes: 0

seshuk
seshuk

Reputation: 182

How are you finding if its written or not? I mean if the other end is an app listening? then is it looking for a CrLf? can you add New Line to the string and send it to Write and see? If that works? Coz writeline and write both should work similar except for the new line.

Upvotes: 1

Louis Ricci
Louis Ricci

Reputation: 21106

WriteLine will append a new line character to the string. Perhaps this "flushes" a buffer to get the printer to respond to the input.

Upvotes: 1

Related Questions