Can anyone help me out with the code. I'm getting the Null Reference Object Exception at the following line

textFile1_Paras[paraNumber] = line;

I'm trying to separate paragraphs from a text file into string array

int paraNumber = 0;
            string[] lines = File.ReadAllLines(filePath1);

            foreach (string line in lines)
            {
                while (line != string.Empty)
                {
                                      
                    textFile1_Paras[paraNumber] = line; 
                    
                }
                paraNumber++;
            }
            MessageBox.Show(textFile1_Paras[paraNumber]);

Recommended Answers

All 4 Replies

probably because you dont check that paraNumber < than the number of available lines. (eg you havent shown where you set textFile1_paras, as an array, it may not be big enough

below is the complete code. Have been trying to bug, didn't think if it has to do something with the paraNumbers < checks...

string[] textFile1_Paras = null;

        //Reading file contents to separate each individual paragraph into string
        private void identifyParas()
        {
            int paraNumber = 0;
            string[] lines = File.ReadAllLines(filePath1);

            foreach (string line in lines)
            {
                while (line != string.Empty)
                {
                    //string[] words = line.Split(delim, StringSplitOptions.RemoveEmptyEntries);
                    // here you've got all your words in that array. Do what you want with them
                    if (line != "")
                    {
                        textFile1_Paras[paraNumber] = line;
                    }
                    
                }
                paraNumber++;
            }
            MessageBox.Show(textFile1_Paras[paraNumber]);
        }

probably because you dont check that paraNumber < than the number of available lines. (eg you havent shown where you set textFile1_paras, as an array, it may not be big enough

That will be why then, your textFile1_paras is null. You havent initialised it.

Thanks, got that working

That will be why then, your textFile1_paras is null. You havent initialised it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.