Reputation: 1407
System.IndexOutOfRangeException: Index was outside the bounds of the array.
How to solve this error ?
Can anyone know this ?
Below my coding... when execute it produce the error that
System.IndexOutOfRangeException Index was outside the bounds of the array
, only if tried to process this csv file :
Instead I don't have error if tried to process this csv file :
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + "|";
}
row_no++;
csvData += "\n";
}
keys = GetUniqueKey(12).ToUpper();
output = System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv");
StreamWriter csv = new StreamWriter(@output, false);
csv.Write(csvData);
csv.Close();
csv.Dispose();
string toCheck;
using (var fs = new FileStream(output, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default))
{
toCheck = sr.ReadToEnd();
if (toCheck.Contains("ColumnAAA") == false)
{
////Start add new column
int posNewColumn = 2;
string[] CSVDump = File.ReadAllLines(output);
List<List<string>> CSV = CSVDump.Select(x => x.Split('|').ToList()).ToList();
for (int i = 0; i < CSV.Count; i++)
{
if (CSV[i].Count > posNewColumn)
{
CSV[i].Insert(posNewColumn, i == 0 ? "ColumnAAA" : "ColumnAAA");
}
else
{
CSV[i].Add(i == 0 ? "ColumnAAA" : "ColumnAAA");
}
}
File.WriteAllLines(output, CSV.Select(x => string.Join("|", x)));
sr.Close();
////End add new column
}
}
Edit #01
The problem is in this line of code-behind.
The code print correctly the number of rows, but I have error when try print and Split the number of columns :
lines = File.ReadAllLines(System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv"));
rows = lines.Count();
columns = lines[23].Split('|').Count();
Response.Write("Number of rows/columns = " + rows.ToString() + "/" + columns.ToString());
Response.End();
Upvotes: 0
Views: 773
Reputation: 2105
Try this :
lines = File.ReadAllLines(System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv"));
rows = lines.Count();
int i = 0;
foreach (string line in lines)
{
string[] parts = line.Split('|');
foreach (string part in parts)
{
columns = parts.Count();
}
i++;
}
Response.Write("Number of rows/columns = " + rows.ToString() + "/" + columns.ToString());
Response.End();
Upvotes: 1