我的.csv文件看起来像这一行有图像名称,下一行有图像路径,并且没有像这样的行,两行都有不同的分隔符。
COL1, COL2, COL3, "1564,1234","8018,2017,233","235,125,125" D:\Images\2.jpg,D:Images\4.jpg,D:\Images\3.jpg
在引号中的第二行字符串中将被视为单个图像名称。 我的要求是在单个项目中读取imagename和imagepath,并且我需要创建行项目并将其绑定到数据行。
我在Bold的线上得到索引超出范围异常,它是图像tittle给7项和图像路径线给3项。 任何人都可以帮助我。
我创建了List<list<myImage>>
,但它无效。
private List<List<MyImage>> rowItemCollection;
private string[] _columns;
public List<List<MyImage>> ReadCsv(string filepath)
{
List<string> tempstring = new List<string>();
DataTable _mydatatable = new DataTable();
using (StreamReader sr = new StreamReader(filepath))
{
rowItemCollection = new List<List<MyImage>>();
string line;
int lineCount = 0;
while (!sr.EndOfStream && ((line = sr.ReadLine()) != null))
{
var item = line.Split('"');
if (lineCount == 0)
{
_columns = item[0].Split(',');
int lastIndex = _columns.Count() - 1;
if (_columns[lastIndex].Contains('\r'))
{
_columns[lastIndex] = _columns[lastIndex].Replace("\r", "");
}
//lineCount++;
}
else if ((lineCount % 2) != 0)
{
foreach (var Imagetittle in item)
{
if (!(string.IsNullOrWhiteSpace(Imagetittle)))
{
tempstring.Add(Imagetittle);
}
}
}
else
{
int j = 0;
string[] imagePath = item[0].Split(',');
var _rowitem = new List<MyImage>();
foreach (string Imagetittle in tempstring)
{
**_rowitem.Add(new MyImage(Imagetittle, imagePath[j]));**
j++;
}
rowItemCollection.Add(_rowitem);
tempstring.Clear();
}
lineCount++;
}
}
return rowItemCollection;
}
答案 0 :(得分:0)
您没有多个分隔符,只有,
。您可以使用StreamReader读取文件,并使用您自己的方法解析每一行。
或者您可以依靠DataDriver来完成工作。
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Collections.Generic;
namespace LoadingCSVFile_44078546
{
class Program
{
static void Main(string[] args)
{
DoItAgain(@"M:\StackOverflowQuestionsAndAnswers\LoadingCSVFile_44078546\sample.txt");
}
private static DataTable DoItAgain(string path)
{
string folderPath = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"" + folderPath +
"\";Extended Properties=\"text;HDR=Yes;FMT=Delimited;\"";
DataTable dt = new DataTable();
try
{
OleDbConnection objConn = new OleDbConnection(connectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("select * from [" + fileName + "]", objConn);
OleDbDataAdapter objAdapter = new OleDbDataAdapter();
objAdapter.SelectCommand = objCmdSelect;
objAdapter.Fill(dt);
objConn.Close();
}
catch (Exception ex)
{
//Do something
}
List<string> tmpList = new List<string>();
if (dt.Rows.Count > 0)
{
foreach (DataRow item in dt.Rows)//ietrate through the record set
{
for (int i = 0; i < dt.Columns.Count; i++)//iterate throught the columns a the record
{
/*
* I don't know how you want to validate the path
* So here's something you should replace with your own
*/
if (item[i].ToString().Contains("\\"))
{
tmpList.Add(item[i].ToString());//add the path to the List<>
}
}
}
}
/*
* tmpList now hold the image paths
*/
return dt;
}
}
}