# [.net] Checking for newline in C#

This topic is 4200 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi! I've got two functions, one that converts commands sent by the MSN Messenger server (which are put into arrays when they're received in my program) to strings, and one to check for newline. Problem is that the newline checking function never returns true! Can someone help?
        /// <summary>
/// Used to get the Command array as a string.
/// </summary>
/// <returns>A string representing the contents of the
/// Command array.</returns>
public String CommandToString()
{
String TmpStr = "";

for (int i = 0; i < Command.Length; i++)
TmpStr = TmpStr + Command[i];

return TmpStr;
}

/// <summary>
/// Converts the Command array to a string, and returns true if it
/// contains a newline at the end of it.
/// </summary>
/// <returns>True or false, depending on the existence
/// of a newline at the end.</returns>
public Boolean CommandHasNewline()
{
String TmpStr = CommandToString();

for (int i = 1; i < TmpStr.Length - 1; i++)
{
if (TmpStr.Substring(i, 2) == System.Environment.NewLine)
{
System.Windows.Forms.MessageBox.Show("TEST!");
return true;
}
}

return false;
}

The reason I'm checking for 2 letters is that I was told that System.Environment.Newline contains "\r\n" as opposed to "\n".

##### Share on other sites
I have some source code regarding packet parsing for msn messenger.
And by the way, I'm starting up a msn messenger .net client project. Maybe you're interested:

http://forums.fanatic.net.nz/index.php?showtopic=15682 (Project Post)

http://forums.fanatic.net.nz/index.php?showtopic=15628 (Packet Parsing)

I'd be glad to have another .net programmer interested in msn messenger on my team :).

##### Share on other sites
It looks like your function to return a newline looks fine - you can check this in a quick console app:

static void Main(string[] args)
{
string TmpStr = "This is line 1" + Environment.NewLine + "This is line 2";
for (int i = 0; i < TmpStr.Length - 1; i++)
{
Console.WriteLine(TmpStr[i].ToString() + '\t' + ((int)TmpStr[i]).ToString());
if (TmpStr.Substring(i, 2) == System.Environment.NewLine)
{
Console.WriteLine("TEST!");
}
}
}

So it looks like the strings you're checking don't actually contain a NewLine (\r\n) - can you write out the contents of the string char by char, converting them to ints to see that you get ASCII 13,10 CR LF.

PS, depending how many commands are in your Command[] array, you might want to use a StringBuilder.

##### Share on other sites
May I ask why you are using Environment.NewLine when '\n' is perfectly good? Is it an MSN thing?

In any case, try this: -

string myString = "This is line 1\nThis is line 2";if(myString.LastIndexOf("\n") > 0){    // There is a '\n' in the string}else{    // There is no a '\n' in the string}

The same applies Environment.NewLine: -

string myString = "This is line 1\nThis is line 2";if(myString.LastIndexOf(Environment.NewLine) > 0){    // There is a Environment.NewLine in the string}else{    // There is no a Environment.NewLine in the string}

[smile]

##### Share on other sites
argh this is driving me nuts! :(

It doesn't seem like the server is splitting up packets at all, even though I know it is!

Here's the code I modified that reads commands from the server:

		public string ReadCommand(NetworkStream Stream)		{			System.IO.StreamReader Reader = new System.IO.StreamReader(Stream, Encoding.ASCII);						string Result = Reader.ReadLine();			Command = Result.Split(' ');            if (Result.LastIndexOf("\n") == 0)            {                Result = Result + Reader.ReadLine();                Command = Result.Split(' ');                LogFile.WriteLog(Result);            }            //Return in case wanting to check the entire line read.            return Result;		}	}

I'm never getting anything in the logfile, and I'm not getting my entire contactlist either, because the server is splitting up packets.

Am I doing anything wrong?

and yes phb5000, I would be interested! PM me! :)

And thanks guys!

##### Share on other sites
Environment.NewLine is better, as it detects the proper characters for a NewLine depending on the environment. '\n' is not always equivalent.

From Wikipedia:

Software applications and operating systems usually represent the newline with one or two control characters:

Systems based on ASCII or a compatible character set use either LF (Line Feed, 0x0A) or CR (Carriage Return, 0x0D) individually, or CR followed by LF (CR+LF, 0x0D 0x0A); see below for the historical raison d'être of the CR+LF convention.
LF: Unix and Unix-like systems, Linux, AIX, Xenix, Mac OS X, BeOS, Amiga, RISC OS and others
CR+LF: CP/M, MP/M, DOS, Microsoft Windows
CR: Commodore machines, Apple II family and Mac OS through version 9

EBCDIC systems—mainly IBM mainframe systems, including z/OS (OS/390), i5/OS (OS/400)—use NEL (Next Line, 0x15) as the newline character. Note that EBCDIC also has control characters called CR and LF, but the numerical value of LF differs from the one used by ASCII. Additionally, there are some EBCDIC variants that also use NEL but assign a different numeric code to the character.

OpenVMS uses a record-based file system and stores text files as one record per line. No line terminators are actually stored, but the system can transparently add a terminator to each line when it is retrieved by an application.

Most textual Internet protocols (including HTTP, SMTP, FTP, IRC and many others) mandate the use of ASCII CR+LF (0x0D 0x0A) on the protocol level, but recommend that tolerant applications recognize lone LF as well. In practice, there are many applications that erroneously use the C newline character '\n' instead (see section Newline in programming languages below). This leads to problems when trying to communicate with systems adhering to a stricter interpretation of the standards; one such system is the qmail MTA that actively refuses to accept messages from systems that send bare LF instead of the required CR+LF.

##### Share on other sites
With an Internet application, you don't want the behaviour to depend on your local environment. Look up the protocol and find out if \n or \r\n is the delimiter and check for that.

However, if your client isn't packetising properly that's where the problem lies, not in your string parsing code. If this is a TCP stream your receiving code is borked; if a message is split over two 'packets' (calls to Read/ReadLine) you will return each part seperately, and if a 'packet' contains the parts of two messages you'll mush them together.

You want something that stores the current 'unused' buffer, perhaps:
StringBuilder buf;string GetNextCommand(NetworkStream stream){ string current = stream.ReadToEnd(); int index = current.IndexOf('\n'); if(index >= 0){  // A new line, so there's something to do  current = buf + current;  buf.Length = 0;  buf.Append(current.Substring(index + 1));  return current.Substring(0, index); } else {  // Nothing yet, but remember what we've read  buf.Append(current);  return String.Empty; }}

##### Share on other sites

This topic is 4200 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account

Register a new account