简体   繁体   中英

c# System.ArgumentOutOfRangeException

I'm making program that sends email with some data. I know that the System.ArgumentOutOfRangeException exception means that number in the array/list doesn't exist, but i don't know what i coded wrongly.

Here's a code:

public void SendMail()
{
    StreamReader sr = new StreamReader(path1);
    var lineCount = File.ReadLines(path1).Count();
    List<string> data = new List<string>();
    for (int i = 0; i < lineCount; i++)
    {
       data[i] = sr.ReadLine(); //Error Comes here.
    }
    string finaldata = data[0] + "/n" + data[1] + "/n" + data[2] + "/n" + data[3] + "/n" + data[4] + "/n" + data[5] + "/n" +       
    data[6] + "/n" + data[7] + "/n" + data[8] + "/n" + data[9] + "/n" + data[10];
    var fromAddress = new MailAddress("tutorialvideohd@gmail.com", "From Name");
    var toAddress = new MailAddress("tutorialvideohd@example.com", "To Name");
    const string fromPassword = "*****";
    string subject = "Some Users Data.";
    string body = finaldata;

    var smtp = new SmtpClient
    {
       Host = "smtp.gmail.com",
       Port = 587,
       EnableSsl = true,
       DeliveryMethod = SmtpDeliveryMethod.Network,
       UseDefaultCredentials = false,
       Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
    };

    using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body
    })
    {
        smtp.Send(message);
    }
}

When you do this, it's only creating an empty list:

List<string> data = new List<string>();

So if you try to assign a value using an index, you're trying to assign a value to something that doesn't exist.

Instead you should Add() as follows:

data.Add(sr.ReadLine());

EDIT:

Also, unrelated to the question asked, but I don't see you closing the StreamReader you've opened, which is always a bad practice. I suggest, instead, using a using statement which will take care of the opening and closing of the StreamReader for you. Also, getting the lineCount is redundant, you could do something like this taking advantage of the fact that you don't need to set the number of items in a list in advance.

List<string> data = new List<string>();
using (StreamReader sr = new StreamReader(path1))
{
    while(!sr.EndOfStream)
        data.Add(sr.ReadLine()); 
}

First, you have an empty list of strings, you can't fill data with by accessing the indexes, since those indexes don't yet exist. You have to use data.Add(sr.ReadLine()) to create the new index and add the value in it.

string finaldata = data[0] + "/n" + data[1] + "/n" + data[2] + "/n" + data[3] + "/n" + data[4] + "/n" + data[5] + "/n" +       
data[6] + "/n" + data[7] + "/n" + data[8] + "/n" + data[9] + "/n" + data[10];

Hardcoded IDs will mean you need at least 11 items in the list and it will break if you have less. Why don't you do this instead?

string finalData = String.Join("/n", data);

This way it joins your list of strings, using the newline as a separator and doesn't matter if you have more or less items in the list.

You are setting an item in the array list that has not yet been initialized. Use the following line where the exception is thrown.

data.Add(sr.ReadLine());

You are doing the same thing twice.

This block of code:

StreamReader sr = new StreamReader(path1);
// ... you had some code here, but not relevant to the point...
for (int i = 0; i < lineCount; i++)
{
    data[i] = sr.ReadLine(); //Error Comes here.
}

Populates the list data with a bunch of strings.

This block of code:

var lineCount = File.ReadLines(path1).ToList();

Populates lineCount with exactly the list of strings that you're trying to fill into data .

So just do this:

StreamReader sr = new StreamReader(path1);
var lineCount = File.ReadLines(path1).Count();
List<string> data = lineCount;

And get rid of this block of code:

for (int i = 0; i < lineCount; i++)
{
    data[i] = sr.ReadLine(); //Error Comes here.
}

And notice how data is now properly filled in. You really don't need to have that StreamReader either, but hey, I don't want to rewrite your entire body of code at this point.

Key takeaway: read the documentation, try to understand what each function call is doing, especially the .NET Framework ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM