Click here to Skip to main content
15,904,024 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
hi guys i'm new user. i have a problem in this error please anyone can help me?
C#
    protected void Button1_Click(object sender, EventArgs e)
    {

        String[] SinhalaWords = new String[70130];
        int count = 0;
        String Word;
        String path = Server.MapPath("~\\Resarch\\new.txt");
        StreamReader sre = new StreamReader(path);

        while ((Word = sre.ReadLine()) != null)
        {
            SinhalaWords[count] = (Word.ToString().Trim());        
         
           TextBox1.Text = SinhalaWords[count];//this line show Index was outside the bounds of the array. error
           count++;
        }
   
       
     
    

    }
}


What I have tried:

index was outside the bounds of the array. c# i want to read this text file and store all text file content in to the array. finally i want display all the array element values in the text box
Posted
Updated 26-Mar-16 0:46am

Stop using "magic numbers" like "70130" in your code - they make it very hard to maintain, and are prone to problems like this.
And in this case, your code is pretty bad - you set the textbox to every single line of the file, and always overwrite the last one.
Your code could easily be replaced with:
C#
string[] SinhalaWords = File.ReadAllLines(Server.MapPath("~\\Resarch\\new.txt"));
TextBox1.Text = SinhalaWords[SinhalaWords.Length - 1];
Which wouldn't have the problem and would work a whole lot faster!
 
Share this answer
 
Quote:
Index was outside the bounds of the array.
It simply mean that your text file have more than 70130 words.
Either you know the number of words and size the array accordingly, or you resize on fly with something like.
C#
SinhalaWords.add(Word.ToString().Trim());

Adding values to a C# array - Stack Overflow[^]
 
Share this answer
 
This exception occurred when you are trying to get any ITEM from specific Index from an array which is not present in array.
so in your case, your array length is '70130' but if your textfile contents are more than specified length your application may throw an exception
I think you need to remove HARDCODED logic of '70130' number and put some different
What you want to do exactly ? which output you want ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900