How to import csv files in C# web application and perform validations checking
-
22 martie 2010 11:25
How to import csv file in C# web application and perform validations checking .
Please let me know the approach.
Thanks in advance.
Toate mesajele
-
22 martie 2010 15:16
Here you go...
private void loadCsvData(string fileName) { FileInfo fileIn = new FileInfo(fileName); StreamReader reader = fileIn.OpenText(); string[] lineIn; while (!reader.EndOfStream) { lineIn = reader.ReadLine().Split(','); //Validate values here } reader.Close(); }- Propus ca răspuns de StLuisRey 23 martie 2010 13:39
- Marcat ca răspuns de SamAgainModerator 29 martie 2010 04:06
-
23 martie 2010 12:45
Use ADO with the Microsoft.Jet.OLEDB provider:
private static DataTable readCSV(string filename) {
string path = System.IO.Path.GetDirectoryName(filename);
string file = System.IO.Path.GetFileName(filename);
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + path + "';Extended Properties='text;HDR=Yes;FMT=Delimited'")) {
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " + file, conn);
da.Fill(dt);
}
return dt;
}- Propus ca răspuns de M.L. Somers 23 martie 2010 12:45
- Marcat ca răspuns de SamAgainModerator 29 martie 2010 04:06
-
16 ianuarie 2011 14:48How to fill all data from csv into untyped dataset?here i am not able to insert string into datetime column.it gives null if first row is datetime and next column is string .
-
5 martie 2012 18:28It is a good way, but this does not work on 64bit machine.
I prefer StreamReader with Regex. -
5 martie 2012 18:36
Maybe this helps too.
void lines(string path)
{
string quoteText = "\"";
string fieldDelimiter = ",";Regex regex = new Regex(String.Format("{0}(?<field>[^{0}]*){0}|(?<field>[^{1}]*)", quoteText, fieldDelimiter), RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
int fieldGroupIndex = regex.GroupNumberFromName("field");
using (StreamReader csv = new StreamReader(path))
{
string lineText;
List<string> row = new List<string>();
while ((lineText = csv.ReadLine()) != null)
{
MatchCollection m = regex.Matches(lineText);
for (int i = 0; i < m.Count; i += 2)
{
row.Add(m[i].Groups[fieldGroupIndex].Value);
// check the values.
}row.Clear();
}
}
}