经过几次尝试,我无法让StreamWriter构建/工作,因此我做了一些根本错误的事情(C#,Visual Studio)
我有一个现有的TCP客户端连接并充当读卡器,这是无故障的工作 -
private System.Net.Sockets.NetworkStream ns;
private System.IO.StreamReader sr;
private string strIP;
private string strPort;
public System.Net.Sockets.TcpClient tc;
public Socketclient(Reader.Search objSearch)
{
m_search = objSearch;
}
public void EthernetConnection()
{
try
{
bool flag = !System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\IPAddress.txt");
if (!flag)
{
System.IO.TextReader textReader = System.IO.File.OpenText(System.Windows.Forms.Application.StartupPath + "\\IPAddress.txt");
string s = textReader.ReadLine();
textReader.Close();
char[] chArr = new char[] { ';' };
string[] sArr = s.Split(chArr);
strPort = sArr[0];
strIP = sArr[1];
flag = strIP == System.String.Empty || strPort == System.String.Empty;
if (!flag)
{
int i = System.Convert.ToInt16(strPort);
tc = new System.Net.Sockets.TcpClient(strIP, i);
flag = !tc.Connected;
if (!flag)
{
ns = tc.GetStream();
sr = new System.IO.StreamReader(ns);
m_search.threadClient = new System.Threading.Thread(new System.Threading.ThreadStart(ReceiveData));
m_search.threadClient.Priority = System.Threading.ThreadPriority.Lowest;
m_search.threadClient.Name = "Ethernet Thread";
}
然后我想添加(在另一个.cs,它是同一个应用程序的一部分)一个StreamWriter线程,将一些字符写回到同一个端口,然后关闭StreamWriter线程(让读者继续运行) -
private System.IO.StreamWriter sw;
string line = "TH1/r/n";
using (StreamWriter sw = new StreamWriter(ns));
sw.WriteLine(line);
sw.Flush();
sw.Close();
以某种方式(我认为)需要参考
ns = tc.GetStream();
任何人都赞赏
此致 活性
答案 0 :(得分:0)
已经多次询问过这类问题。
Receving and sending data in C#
上面的示例简要介绍和过去显示数据的发送
using(TcpClient tcpClient = new TcpClient("ADDRESS"))
{
NetworkStream networkStream = tcpClient.GetStream();
using(StreamWriter streamWriter = new StreamWriter(networkStream))
{
streamWriter.WriteLine(data);
}
}
答案 1 :(得分:0)
问题是StreamWriter周围的使用块,删除它允许底层流继续。