1

I'm trying to design a check on incoming strings for an array, and if the incoming string has a specific starting character it gets skipped over

For example:

;item1
item2
item3
;item4

should be put into array as

item2
item3

I thought I'd try to use a foreach method to skip the line that starts with the identifier, and then in the else append the lines that don't match back into the string array, but it doesn't seem I am able to do this.

Help!

    void Whitelist()
    {
        if (logging == 1)
        {
            FIO._Log("Performing WhiteList func", writer);
        }
        try
        {
            string[] lines = File.ReadAllLines("Whitelist.ini");
            string[] lines2;
            foreach (string line in lines)
            {
                if (line.StartsWith(";"))
                {
                    continue;
                }
                else
                {
                    // lines2.append(line) ??
                }

            }
            structs.CustomWhiteList = lines2;
        }
        catch (Exception e)
        {
            MessageBox.Show("Error reading whitelist file." + Environment.NewLine + e.Message);
            FIO._Log("Failed to read whitelist file", writer);
        }
    }
2
  • Use IEnumerable.Where Commented Aug 4, 2014 at 3:10
  • You have an array, not a list. There's no "Add" or "Append" method. But everything can be shortened to lines2 = lines.Where(l => !l.StartsWith(";")); Commented Aug 4, 2014 at 3:11

1 Answer 1

2

You can read the lines in, filter out the ones starting with a semicolon, and then set the resulting array directly to CustomWhiteList.

Try the following code:

var lines = File.ReadAllLines("Whitelist.ini");

structs.CustomWhiteList = lines.Where(x => !x.StartsWith(";")).ToArray();

This uses LINQ, so you'll have to add using System.Linq to your class if it's not already there.

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

1 Comment

Oh my goodness, thank you! Everyone had good answers, but this one was so simple, and you answered me so fast.

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.