IP打印机控制

public static bool tcpPrintCode(string PrinterPort, byte[] cmdBytes)
{
// PrinterPort // ip address
if (PrinterPort.Trim() == string.Empty) return false;

bool result = false;
TcpClient tcp = new TcpClient();
string TcpIpAddress = PrinterPort.Trim();
int TcpPort = 9100;
try
{
tcp.Connect(System.Net.IPAddress.Parse(TcpIpAddress), TcpPort);
// tcp = TimeoutSocket.Connect(string.Empty, TcpIpAddress, TcpPort, 1000);
tcp.SendTimeout = 1000;
tcp.ReceiveTimeout = 1000;
if (tcp.Connected)
{
tcp.Client.Send(cmdBytes);
result = true;
}
}
catch
{
// throw new Exception("打印失败,请检查打印机或网络设置。", ex);
}
finally
{
if (tcp != null)
{
if (tcp.Client != null)
{
tcp.Client.Close();
tcp.Client = null;
}
tcp.Close();
tcp = null;
}
}
// Thread.Sleep(1000);
return result;
}


byte[] cmdBytes = Txt2Byte(CommString);

public static byte[] Txt2Byte(string str)
{
return System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
}

public static byte[] Str2Byte(string str)
{
return System.Text.Encoding.GetEncoding("ascii").GetBytes(str);
}