5

I am somehow unable to determine whether a string is newline or not. The string which I use is read from a file written by Ultraedit using DOS Terminators CR/LF. I assume this would equate to "\r\n" or Environment.NewLine in C#. However , when I perform a comparison like this it always seem to return false :

if(str==Environment.NewLine)

Anyone with a clue on what's going on here?

5 Answers 5

7

How are the lines read? If you're using StreamReader.ReadLine (or something similar), the new line character will not appear in the resulting string - it will be String.Empty or (i.e. "").

Sign up to request clarification or add additional context in comments.

2 Comments

Daniel got the correct answer. File.ReadAllLine won't include the newline into the string. So you should actually check for String.Empty.
when you use File.ReadAllLines, why do you care about '\n'. You will not get that. Instead you'll get all the lines in a string array split by '\n'. check if File.ReadAllText serves your purpose.
6

Are you sure that the whole string only contains a NewLine and nothing more or less? Have you already tried str.Contains(Environment.NewLine)?

Comments

2

The most obvious troubleshooting step would be to check what the value of str actually is. Just view it in the debugger or print it out.

Comments

2

Newline is "\r\n", not "/r/n". Maybe there's more than just the newline.... what is the string value in Debug Mode?

You could use the new .NET 4.0 Method: String.IsNullOrWhiteSpace

Comments

1

This is a very valid question.

Here is the answer. I have invented a kludge that takes care of it.

static bool StringIsNewLine(string s)
{
    return (!string.IsNullOrEmpty(s)) &&
        (!string.IsNullOrWhiteSpace(s)) &&
        (((s.Length == 1) && (s[0] == 8203)) || 
        ((s.Length == 2) && (s[0] == 8203) && (s[1] == 8203)));
}

Use it like so:

foreach (var line in linesOfMyFile)
{
  if (StringIsNewLine(line)
  {
    // Ignore reading new lines
    continue;
  }

  // Do the stuff only for non-empty lines
  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.