Question

I have a text file which I split with a \n.

text file (test) reads

1
2
3
4

now the confusing part.

code

string test = System.IO.File.ReadAllText(@"C:\Custom tests\"+testselect.Text+".txt");

string[] check = test.Split('\n');

if (check[0] == "1")
{
     label.Text = "whatever";
}

this does not work. The label stays default value. however if I :

label.Text = check[0];

the label displays a 1.

I do not understand this please help.

Was it helpful?

Solution

First - you should be able to just use File.ReadAllLines instead of reading the text and splitting....

You may need to trim the results. If there is extra whitespace on the lines, the condition may fail. Try using:

if (check[0].Trim() == "1")
{

This will trim off any whitespace, which should cause your conditional to succeed.

You can also put a breakpoint in, and inspect the values in the debugger. This will help you better diagnose the issue.

OTHER TIPS

I believe that you should use Environment.NewLine. Different operating systems use different newline characters.

What is the universal newline for all operating systems? (LF and CR)

Are you just comparing numbers? Need to check case and whitespace..

string.Equals(check[0].Trim(), "some value", StringComparison.OrdinalIgnoreCase);

You could use something like this:

Remove the returns if there are any

string[] check = test.Replace("\r", "").Split('\n');

        if(check[0] == "1")

or split by new line and take the character in the array and check that.

string[] check = test.Split('\n');

        if(check[0][0] == '1')

I would use option two.

EDIT:

Or something like this, but its a bit OTT and you get all of the \r\n

 char[] check = test.SplitMeUp();

        if(check[0] == '1')


 static class Extensions
{
    public static char[] SplitMeUp(this string str)
    {
        char[] chars = new char[str.Length];
        for (int i = 0; i < chars.Length; i++)
            chars[i] = str[i];

        return chars;
    }
}

EDIT:

Something else to filter out specific characters

public static char[] SplitMeUp(this string str, char[] filterChars = null)
    {
        List<Char> chars = new List<char>();
        for (int i = 0; i < str.Length; i++)
        {
            if(filterChars != null && filterChars.Length > 0 && filterChars.Contains(str[i]))
                    continue; 

            chars.Add(str[i]);
        }

        return chars.ToArray();
    }

and use it like

char[] check = test.SplitMeUp(new char[] {'\r', '\n'});

        if(check[0] == '1')

it will ignore all of those \r\n and just split everything up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top