简体   繁体   English

c#System.ArgumentOutOfRangeException

[英]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. 我知道System.ArgumentOutOfRangeException异常意味着数组/列表中的数字不存在,但是我不知道我写错了什么。

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: 相反,您应该如下所示Add()

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. 另外,与提出的问题无关,但我看不到您关闭了已打开的StreamReader ,这始终是一个坏习惯。 I suggest, instead, using a using statement which will take care of the opening and closing of the StreamReader for you. 我建议改为使用using语句,该语句将为您处理StreamReader的打开和关闭。 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. 另外,获取lineCount是多余的,您可以利用这样的事实来进行以下操作:不需要预先设置列表中的项目数。

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. 首先,您有一个空字符串列表,您无法通过访问索引来填充data ,因为这些索引尚不存在。 You have to use data.Add(sr.ReadLine()) to create the new index and add the value in it. 您必须使用data.Add(sr.ReadLine())创建新索引并在其中添加值。

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. 硬编码ID意味着您至少需要11项,如果数量少了,它将中断。 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. 用一串字符串填充列表data

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 . 精确地使用您要填充到data中的字符串列表填充lineCount

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. 并注意现在如何正确填充data 。您确实也不需要该StreamReader ,但是,嘿,我现在不想重写整个代码。

Key takeaway: read the documentation, try to understand what each function call is doing, especially the .NET Framework ones. 关键要点:阅读文档,尝试了解每个函数调用的功能,尤其是.NET Framework的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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