Import CSV file to datatable then export specific columns back to new CSV

Costas

Administrator
Staff member
JavaScript:
private void button1_Click(object sender, EventArgs e)
{
	if (txtDAT.Text.Length == 0 || txtTicketNo.Text.Trim().Length == 0)
	{
		MessageBox.Show("Please fill all the textboxes!");
		return;
	}

	if(!File.Exists(txtDAT.Text))
	{
		MessageBox.Show(txtDAT.Text + "\r\n not exists!");
		return;
	}

	DataTable dt = General.ImportDelimitedFile(txtDAT.Text, "|", false);

	List<rowD> lst = dt.AsEnumerable().Select(row => new rowD()
	{
		recID = row.Field<string>("no0"),
		customerSource = row.Field<string>("no78"),
		customerType = row.Field<string>("no80"),
		company = row.Field<string>("no89"),
	}
	).ToList();

	string baseDIR = Path.GetDirectoryName(txtDAT.Text) + Path.DirectorySeparatorChar;

	//CustomerSource
	List<string> customerSourceCSV = lst.Select(x => string.Format("{0}|{1}|{2}|{3}", x.recID, x.customerSource, x.customerType, x.company)).ToList();

	string customerSourceDir = baseDIR + "customerSource" + Path.DirectorySeparatorChar;
	Directory.CreateDirectory(customerSourceDir);

	File.WriteAllLines(customerSourceDir + string.Format("Customer_{0}.dat", txtTicketNo.Text), customerSourceCSV);
}

private class rowD
{
	public string recID { get; set; }
	public string customerSource { get; set; }
	public string customerType { get; set; }
	public string company { get; set; }
}



public static DataTable ImportDelimitedFile(string filename, string delimiter, bool first_is_column_names)
{

	DataTable dt = new DataTable();


	using (StreamReader file = new StreamReader(filename)) {
		//read the first line
		string line = file.ReadLine();

		if (line == null)
			return null;

		//split the first line to create columns to datatable!
		string[] columns = line.Split(Convert.ToChar(delimiter));// Regex.Split(line, "|");

		for (int i = 0; i < columns.Count(); i++) {
			if (first_is_column_names)
				dt.Columns.Add(columns[i].Replace("\"", ""));
			else
				dt.Columns.Add("no" + i.ToString());
		}

		if (!first_is_column_names) {
			//rewind reader to start!
			file.DiscardBufferedData();
			file.BaseStream.Seek(0, SeekOrigin.Begin);
			file.BaseStream.Position = 0;
		}

		while ((line = file.ReadLine()) != null) {
			if (line.Trim().Length > 0) {
				line = line.Replace("\"", "");
				string[] rows = line.Split(Convert.ToChar(delimiter));//Regex.Split(line, delimiter);
				dt.Rows.Add(rows);

			}
		}


	}

	return dt;
}
 
Top