将文本文件直接发送到网络打印机

时间:2013-09-09 18:45:28

标签: c# printing network-printers

我目前正在使用的代码通过编写临时文件将原始数据发送到打印机,然后使用File.Copy()将其发送到打印机。 File.Copy()支持本地端口,如LPT1和共享打印机,如\\FRONTCOUNTER\LabelPrinter

但是,现在我正在尝试使用直接在网络上的打印机:192.168.2.100,我无法弄清楚要使用的格式。

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

我知道可以从每台计算机上“添加一台打印机”,但我希望避免这种情况 - 上面的第二行代码可以自动从网络上的任何计算机上运行,​​无需配置。我也知道可以P / Invoke windows打印假脱机程序,如果这是我唯一的选择,我可以接受它,但这比我想要的代码开销要多得多。

理想情况下,某人可能有办法让File.Copy()工作,或者有类似的C#语句接受网络IP。

2 个答案:

答案 0 :(得分:19)

您可以使用套接字并将数据直接发送到该IP地址。应该与File.Copy几乎相同。我只是试了一下,这很有用。

我刚发了一些文字,但这里是我用过的代码

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();

答案 1 :(得分:0)

尝试此代码:

public class PrintHelper
{
    private readonly IPAddress PrinterIPAddress;

    private readonly byte[] FileData;

    private readonly int PortNumber;
    private ManualResetEvent connectDoneEvent { get; set; }

    private ManualResetEvent sendDoneEvent { get; set; }

    public PrintHelper(byte[] fileData, string printerIPAddress, int portNumber = 9100)
    {
        FileData = fileData;
        PortNumber = portNumber;
        if (!IPAddress.TryParse(printerIPAddress, out PrinterIPAddress))
            throw new Exception("Wrong IP Address!");
    }

    public PrintHelper(byte[] fileData, IPAddress printerIPAddress, int portNumber = 9100) 
    {
        FileData = fileData;
        PortNumber = portNumber;
        PrinterIPAddress = printerIPAddress;
    }

    /// <inheritDoc />
    public bool PrintData()
    {
        //this line is Optional for checking before send data
        if (!NetworkHelper.CheckIPAddressAndPortNumber(PrinterIPAddress, PortNumber))
            return false;
        IPEndPoint remoteEP = new IPEndPoint(PrinterIPAddress, PortNumber);
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.NoDelay = true;
        connectDoneEvent = new ManualResetEvent(false);
        sendDoneEvent = new ManualResetEvent(false);

        try
        {
            client.BeginConnect(remoteEP, new AsyncCallback(connectCallback), client);
            connectDoneEvent.WaitOne();
            client.BeginSend(FileData, 0, FileData.Length, 0, new AsyncCallback(sendCallback), client);
            sendDoneEvent.WaitOne();
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            // Shutdown the client
            this.shutDownClient(client);
        }
    }

    private void connectCallback(IAsyncResult ar)
    {
        // Retrieve the socket from the state object.
        Socket client = (Socket)ar.AsyncState;

        // Complete the connection.
        client.EndConnect(ar);

        // Signal that the connection has been made.
        connectDoneEvent.Set();
    }

    private void sendCallback(IAsyncResult ar)
    {
        // Retrieve the socket from the state object.
        Socket client = (Socket)ar.AsyncState;

        // Complete sending the data to the remote device.
        int bytesSent = client.EndSend(ar);

        // Signal that all bytes have been sent.
        sendDoneEvent.Set();
    }
    private void shutDownClient(Socket client)
    {
        client.Shutdown(SocketShutdown.Both);
        client.Close();
    }
}

网络助手类:

public static class NetworkHelper
    {
        public static bool CheckIPAddressAndPortNumber(IPAddress ipAddress, int portNumber)
        {
            return PingIPAddress(ipAddress) && CheckPortNumber(ipAddress, portNumber);
        }
        public static bool PingIPAddress(IPAddress iPAddress)
        {
            var ping = new Ping();
            PingReply pingReply = ping.Send(iPAddress);

            if (pingReply.Status == IPStatus.Success)
            {
                //Server is alive
                return true;
            }
            else
                return false;
        }
        public static bool CheckPortNumber(IPAddress iPAddress, int portNumber)
        {
            var retVal = false;
            try
            {
                using (TcpClient tcpClient = new TcpClient())
                {
                    tcpClient.Connect(iPAddress, portNumber);
                    retVal = tcpClient.Connected;
                    tcpClient.Close();
                }
                return retVal;
            }
            catch (Exception)
            {
                return retVal;
            }

        }
    }