流编写器未将修剪后的文本写入 C# 中的文件

发布于 2024-11-15 19:48:43 字数 1187 浏览 2 评论 0原文

我有一个奇怪的问题。我从 TCP 客户端获取文本流并将其写入文件。流没有完全填充,因此在将其转换为字符串时,字节数组的未填充部分被转换为 \0 所以我最终得到了,

str = "blah foo bar \0\0\0\0\0...";

所以我所做的是

str = str.trim('\0');

但是如果我这样做,那么字符串不会被写入使用流编写器的文件。如果我评论修剪线,那么它会与所有空白字符一起写入。这是我的完整代码

StreamWriter sw = new StreamWriter("c:\\a\\ta.txt");
while (true)
{
    try
    {
        NetworkStream ns = tc.GetStream();
        byte[] instream = new byte[tc.ReceiveBufferSize];
        Thread.Sleep(2500);
        ns.Read(instream, 0, tc.ReceiveBufferSize);
        string decodedData = string.Empty;
        decodedData = System.Text.Encoding.ASCII.GetString(instream);
        decodedData = decodedData.Trim('\0');
        //string a = "dfdsfdsfdsfdsf";
        //string b = a.Trim('\0');

        try
        {
            sw.Write(decodedData);
            //MessageBox.Show(decodedData);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

有人可以解释一下为什么会这样以及我如何解决这个问题。

哦,在调试时,我可以看到解码的数据具有整齐干净的修剪文本,但我不知道为什么它没有被写入文件。

I have a strange problem. I am getting a stream of text from a tcp client and writing it to a file. The stream is not fully filled hence while converting it to string the unfilled parts of the byte array are converted to \0 so i finally end up having,

str = "blah foo bar \0\0\0\0\0...";

so what i did is

str = str.trim('\0');

But if i do this then the string is not getting written to a file using stream writer. If i comment the trim line then its getting written along with all the white space characters. Here is my full code

StreamWriter sw = new StreamWriter("c:\\a\\ta.txt");
while (true)
{
    try
    {
        NetworkStream ns = tc.GetStream();
        byte[] instream = new byte[tc.ReceiveBufferSize];
        Thread.Sleep(2500);
        ns.Read(instream, 0, tc.ReceiveBufferSize);
        string decodedData = string.Empty;
        decodedData = System.Text.Encoding.ASCII.GetString(instream);
        decodedData = decodedData.Trim('\0');
        //string a = "dfdsfdsfdsfdsf";
        //string b = a.Trim('\0');

        try
        {
            sw.Write(decodedData);
            //MessageBox.Show(decodedData);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Can some one explain me why this is and how i can solve htis out.

oh on debugging i can see that decodedData has the trimmed text neat and clean but i dont know why its not being written to the file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小姐丶请自重 2024-11-22 19:48:43

这里存在三个问题。

首先,您从整个数组中获取文本,无论您实际收到了多少字节。这很可能是您的零字符的来源。

要解决此问题,请按如下方式更改代码:

int actuallyRead = ns.Read(instream, 0, tc.ReceiveBufferSize);
string decodedData = Encoding.ASCII.GetString(instream, 0, actuallyRead);

其次,您需要关闭流以使其刷新其内容。最好的方法是将其包装在 using 块中:

using (StreamWriter sw = new StreamWriter("c:\\a\\ta.txt"))
{
    ... rest of your code here
}

第三,代码通常永远不会完成。添加一种不依赖异常处理即可完成的方法,例如:

int actuallyRead = ns.Read(instream, 0, tc.ReceiveBufferSize);
if (actuallyRead == 0)
    break;
string decodedData = Encoding.ASCII.GetString(instream, 0, actuallyRead);

There are three problems here.

First, you grab the text from the whole array, regardless of how many bytes you actually did receive. Most likely this is the source of your zero characters.

To fix that, change the code as follows:

int actuallyRead = ns.Read(instream, 0, tc.ReceiveBufferSize);
string decodedData = Encoding.ASCII.GetString(instream, 0, actuallyRead);

Secondly, you need to close the stream in order for it to flush its contents. The best way to do that is to wrap it in a using block:

using (StreamWriter sw = new StreamWriter("c:\\a\\ta.txt"))
{
    ... rest of your code here
}

Thirdly, the code would normally never complete. Add a way for it to complete without relying on exception handling, for instance:

int actuallyRead = ns.Read(instream, 0, tc.ReceiveBufferSize);
if (actuallyRead == 0)
    break;
string decodedData = Encoding.ASCII.GetString(instream, 0, actuallyRead);
白馒头 2024-11-22 19:48:43

你永远不会刷新作家 - 我怀疑一切都只是缓冲了。您应该为您的 StreamWriter 使用 using 语句,以便在您离开该块时将其释放。然后这将刷新文件。

您还应该查看从 Stream.Read 返回的值,并仅使用实际已读取的缓冲区部分创建字符串。

最后,鉴于您有一个 while(true) 循环,目前尚不清楚您期望如何终止。目前,只有在遇到异常时才会终止。如果 ns.Read 返回 0,您可能应该终止。

You're never flushing the writer - I suspect everything's just buffered. You should use a using statement for your StreamWriter, so that it gets disposed when you leave the block. That will then flush the file.

You should also look at the value returned from Stream.Read, and only create a string using the portion of the buffer which has actually been read.

Finally, it's not clear how you expect this to terminate, given that you've got a while(true) loop. You're currently only going to terminate when you get an exception. You should probably terminate if ns.Read returns 0.

你爱我像她 2024-11-22 19:48:43

试试这个:

decodedData = new string(decodedData.ToCharArray());

IIRC,字符串构造函数将修剪尾随的 NULL 终止符。

Try this:

decodedData = new string(decodedData.ToCharArray());

IIRC, the string constructor will trim trailing NULL terminators.

多彩岁月 2024-11-22 19:48:43

你试过吗...

 decodedData = decodedData.Trim(@"\0");

have you tried...

 decodedData = decodedData.Trim(@"\0");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文