lukevp / ESC-POS-.NET

Efficient, Easy to Use Thermal Printing & POS (Windows/Linux/OSX, WiFi/BT/USB/Ethernet)
MIT License
523 stars 171 forks source link

USB Printer: 'Access to the path 'COM4' is denied' #231

Closed AntonioBaez13 closed 1 year ago

AntonioBaez13 commented 1 year ago

Hi, I'm getting the following issue when printing. The first time I print something I manage to print the ticket without any issues, but the second time I try to print, then I get the error "Access to the path 'COM4' is denied" Here is what my code looks like

`  public void PrintTicket()
        {
            var printer = new SerialPrinter(portName: "COM4", baudRate: 9600);
            var e = new EPSON();
            printer.Write(PrintPOSReceipt(e));
        }`
lukevp commented 1 year ago

Are you making a new printer every time you print? Try storing a single reference to the printer and reusing that.

AntonioBaez13 commented 1 year ago

Thanks for the quick reply @lukevp and also thanks for creating this amazing library :) I did try the following (See code snippet) which also didn't work, but instead of getting the "Access denied error" the app wasn't printing anything at all without throwing any exceptions or anything.

private static SerialPrinter printer = new SerialPrinter(portName: "COM4", baudRate: 9600);
  public void PrintTicket()
        {
            var e = new EPSON();
            printer.Write(PrintPOSReceipt(e));
        }
lukevp commented 1 year ago

Thank you for the kind words!

One of the common pitfalls with this library is around the way it queues up writes. When you call Write, it doesn't actually write it to the printer immediately, because the printer may hang up, overflow its buffer, be out of paper, etc. it's a lot easier to allow those error conditions to be fixed and then the writes can continue once they are. It helps compartmentalize some of the error conditions you get from integrating with a physical piece of hardware.

Most apps that people write are long-running, so as long as the app is running, these background tasks will flush the underlying stream and write bytes to it. If you make a test console app that writes to the printer and immediately closes, then you won't necessarily see output. One way to do this in a test app is just to put a 1 second sleep before the program terminates. The flushing writes are only a few milliseconds, so that should give it enough time to write.

There are more in depth ways to determine when a write is complete, but it's probably not necessary for what you're trying to do.

AntonioBaez13 commented 1 year ago

My bad, what you suggested before actually did work, I just had forgotten to rebuild the application to apply the latest changes: Reason of failure: I was making a new printer every time I printed Solution: Declare the printer once


  public void PrintTicket()
        {
            var e = new EPSON();
            printer.Write(PrintPOSReceipt(e));
        }```