Send a text file directly to a network printer

I have a working code that sends raw data to the printer, writing a temporary file, and then File.Copy() sends it to the printer. File.Copy() supports both local ports, such as LPT1 and shared printers such as \\FRONTCOUNTER\LabelPrinter .

However, now I am trying to get it to work with a printer that is located directly on the network: 192.168.2.100 , and I cannot figure out which 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 that it is possible to "Add a printer" from each computer, but I hope to avoid this - the second line of code above works automatically from any computer on the network, without the need for configuration. I also know that it is possible for P / Invoke for the Windows print spooler, and if this is my only option, I can accept it, but it is a lot more code overhead than I would like to have.

Ideally, someone will either have a way to make File.Copy() , or a similar C # statement that will take a network IP address.

+4
source share
1 answer

You can use sockets and send data directly to this IP address. To a large extent, this will be the same as File.Copy . I just tried it and it worked.

I just posted some text, but here is the code 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(); 
+16
source

Source: https://habr.com/ru/post/1501349/


All Articles