user3218338
user3218338

Reputation: 682

Array element is maybe not set

In this method below I set string smdrext to tmp[3]. However, tmp[3] seems to sometimes be empty because I get "Index was outside the bounds of the array.". Before I set it, can I change that it really exist to make sure the program does not halt again due to this?

public void WriteToCSV(string line, string path)
{

    string[] tmp = line.Split(',');
    string smdrext = tmp[3];

    if (ext.Contains(Convert.ToString(smdrext)))
    {

      File.AppendAllText(path, line + "\n");

    }

}

Upvotes: 0

Views: 58

Answers (1)

Jayesh Goyani
Jayesh Goyani

Reputation: 11154

Please try with the below code snippet.

public void WriteToCSV(string line, string path)
{
    if (!string.IsNullOrEmpty(line))
    {
        string[] tmp = line.Split(',');
        if (tmp.Length > 3)
        {
            string smdrext = tmp[3];

            if (ext.Contains(Convert.ToString(smdrext)))
            {
                File.AppendAllText(path, line + "\n");
            }
        }
    }

}

Let me know if any concern.

Upvotes: 2

Related Questions