Send text file directly to network printer

Bobson picture Bobson · Sep 9, 2013 · Viewed 28.2k times · Source

I have currently-working code which sends raw data to a printer by writing a temporary file, then using File.Copy() to send it to the printer. File.Copy() supports both local ports, like LPT1 and shared printers like \\FRONTCOUNTER\LabelPrinter.

However, now I'm trying to get it working with a printer that's directly on the network: 192.168.2.100, and I can't figure out the format to use.

File.Copy(filename, @"LPT1", true); // Works, on the FRONTCOUNTER computer
File.Copy(filename, @"\\FRONTCOUNTER\LabelPrinter", true); // Works from any computer
File.Copy(filename, @"\\192.168.2.100", true); // New printer, Does not work

I know it's possible to "Add a printer" from each computer, but I'm hoping to avoid that - the second line of code above works from any computer on the network automatically, with no configuration required. I also know it's possible to P/Invoke the windows print spooler, and if that's my only option I may take it, but that's much more code overhead than I'd like to have.

Ideally, someone will have either a way to make File.Copy() work or a similar C# statement which will accept a network IP.

Answer

Kirk Backus picture Kirk Backus · Sep 10, 2013

You can use sockets and send the data straight to that IP address. Should pretty much be the same as File.Copy. I just tried it out and that worked.

I just sent some text but here is the code that I used

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.NoDelay = true;

IPAddress ip = IPAddress.Parse("192.168.192.6");
IPEndPoint ipep = new IPEndPoint(ip, 9100);
clientSocket.Connect(ipep);

byte[] fileBytes = File.ReadAllBytes("test.txt");

clientSocket.Send(fileBytes);
clientSocket.Close();