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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18704839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:57:53  来源:igfitidea点击:

Send text file directly to network printer

c#printingnetwork-printers

提问by Bobson

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 LPT1and shared printers like \\FRONTCOUNTER\LabelPrinter.

我有当前工作的代码,它通过编写一个临时文件将原始数据发送到打印机,然后File.Copy()用于将其发送到打印机。 File.Copy()支持本地端口,例如LPT1和共享打印机,例如\\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.

但是,现在我试图让它与直接在网络上的打印机一起使用: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

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.

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

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

理想情况下,有人将有一种File.Copy()工作方式或类似的 C# 语句来接受网络 IP。

采纳答案by Kirk Backus

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.

您可以使用套接字并将数据直接发送到该 IP 地址。应该和File.Copy. 我刚刚试了一下,效果很好。

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

回答by saeid mohammad hashem

try this code:

试试这个代码:

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

Network Helper class:

网络助手类:

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;
            }

        }
    }