无法从c#中的字符串中删除CRLF

时间:2014-11-23 06:38:11

标签: c# string parsing newline

我试图从C#代码中的字符串dataFromClient中删除所有CRLF字符。到目前为止,所有以下尝试都失败了,我非常感谢你的帮助:

编辑: 问题是无论何时调用Console.WriteLine(dataFromClient)方法,字符串都会打印出来,但是如下所示:" \ vposition?:X \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 ....."我希望输出只是"位置?:X"。但是还没有能够削减" \ 0"来自字符串。

此代码是我第一次尝试设置一个简单的服务器来接受第三方软件的连接。请求来自客户端,然后此服务器将请求解析为电动笛卡尔阶段理解的命令。

Bellow是控制台应用程序的服务器部分/类的代码。

有我已经尝试的建议的帖子:

Removing carriage return and new-line from the end of a string in c#

Serial communication and CRLF C#

How to WriteAllLines in C# without CRLF

Remove a character from a string

String Trim Spaces doesn't work

以下是代码:

using System;
using System.Net;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace autotile_V001
{
    public class Myserver
    {
        int MyServerPort;
        bool go = true;
        int requestCount = 0;
        string dataFromClient;
        string serverResponse;
        IPAddress ipAddr = IPAddress.Loopback;

        public string process(string s)
        {
            int len = s.Length;
            int current = 0;
            StringBuilder sb = new StringBuilder(len);

            while (current < len - 1)
            {
                if ((s[current] == ' ' && s[current + 1] == ' '))
                {
                    break;
                }
                else
                {
                    sb.Append(s[current]);
                }
                current++;
            }
            return sb.ToString();
        } 

        public void StartMyServer()
        {
            TcpListener serverSocket = new TcpListener(ipAddr, MyServerPort);
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Console.WriteLine(" >> Server Started");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" >> Accepted connection from client");
            requestCount = 0;

            while ((go))
            {
                try
                {
                    requestCount++;
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[(int)clientSocket.ReceiveBufferSize];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);

                    Console.WriteLine(" >> Data from client - {0}", (String.Join("\n", dataFromClient)).Trim());

                    serverResponse = Console.ReadLine();

                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);

                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);

                    go = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());

                    go = false;
                }
            }
        }

        public Myserver(int someData)
        {
            MyServerPort = someData;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

Trim()只删除前导和尾随空格 - 而不是字符串中的空格。

您需要使用Replace从字符串中删除不需要的字符或字符串。在上面的例子中,字节流中的任何试验性非空格字符(可能不可见,例如0x0)将导致Trim的调用不起作用。

var someString = "FOO\r\n\r\n\0";
var strippedTrim = someString.Trim();  // Fail - "FOO\r\n\r\n\0"
var strippedReplace = someString.Replace("\r\n", ""); // "FOO\0"
// .Replace() any other unwanted white space, e.g. "\t"

但请注意,Trim()仍将删除尾随的'\ n'(而不是Windows CRLF),因此不是导致该错误的String.Join("\n"

修改

只是澄清string.Join - string.Join在单个字符串上使用时是多余的/没有效果(它也不会将字符串视为单个字符串的数组)。

var join = string.Join("x", "FOO\r\n\r\n").Trim(); // Works - "FOO"