StreamWriter 的正确使用 [英] Correct use of StreamWriter
问题描述
经过多次尝试后,我无法让 StreamWriter 正确构建/工作,所以我在做一些根本错误的事情(C#、Visual Studio)
After several attempts I can't get StreamWriter to build / work corectly so I am doing something fundamentally wrong (C#, Visual Studio)
我有一个现有的 TCP 客户端,它可以连接并充当读取器,它可以正常工作 -
I have an exisitng TCP Client which connects and acts as a reader, this is working without fault -
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 线程(让读取器运行)-
I then want to add (in another .cs which is part of the same application) a StreamWriter thread to write back some characters to the same port and then close the StreamWriter thread (leaving the reader running) -
private System.IO.StreamWriter sw;
string line = "TH1/r/n";
using (StreamWriter sw = new StreamWriter(ns));
sw.WriteLine(line);
sw.Flush();
sw.Close();
不知何故(我认为)需要参考
Which, somehow (I think) needs to refer back to
ns = tc.GetStream();
任何想法不胜感激
问候活跃
推荐答案
问题是围绕 StreamWriter 的 using 块,删除它允许底层流继续.
The issue was the using block around StreamWriter, removing it allowed the underlying stream to continue.
这篇关于StreamWriter 的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!