Answered by:
Reading CSV File and Generate a text file with chosen columns

Question
-
Hi everybody,
I am new at programming C#.
I tried every code in the internet. They didn't help me that much. That's why i am here to ask my question:
* I have a .csv file with following headers: Name, Surname, Age, Date of Birth, Place
* I want to generate a text file with 3 columns: Name, Surname and Age
How can i generate such a file? I started to program following code just to generate everything as text file. It doesn't work. It generates only an empty text file.. I don't know why..
namespace CsvOkuma2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } OpenFileDialog filedialog = new OpenFileDialog(); StreamWriter File = new StreamWriter("NewText.txt"); private void ButtonGenerate(object sender, EventArgs e) { using (StreamReader sr = new StreamReader(FileAddress.Text, Encoding.Default) ) { readWriteInfo(sr); } } private void Button_Select(object sender, EventArgs e) { SelectFile(FileAddress); } private void readWriteInfo(StreamReader sr) { string currentLine; while ( ( currentLine = sr.ReadLine() ) != null ) { File.Write(currentLine); } } private void SelectFile(TextBox tb, string filter = "CSV files|*.csv|Alle|*.*", bool fileMustExist = true) { filedialog.Filter = filter; filedialog.CheckFileExists = fileMustExist; if (DialogResult.OK == filedialog.ShowDialog()) { tb.Text = filedialog.FileName; } } } }
- Edited by CanAcarDUS Tuesday, September 4, 2018 3:07 PM
Tuesday, September 4, 2018 3:04 PM
Answers
-
Hi CanAcarDUS,
Try the code below to get the single columns. You could set the column you want in columnName string array in the code.
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; using System.Diagnostics; using System.Diagnostics.Eventing.Reader; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using System.IO; using System.IO.Ports; using System.Linq; using System.Management; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; namespace ConsoleApp { public class Program { public static void Main(string[] args) { ////create a csv file //string filePath = @"test.csv"; //string delimiter = ","; //string[][] output = new string[][]{ // new string[]{"Name", "Surname", "Age","Date of Birth","Place"}, // new string[]{"Apple", "A", "10","1990/3/4","USA" }, // new string[]{"Bob", "B", "11","1991/3/4","China" }, // new string[]{"Cherry", "C", "12","1992/3/4","Japan" } // }; //int length = output.GetLength(0); //StringBuilder sb = new StringBuilder(); //for (int index = 0; index < length; index++) // sb.AppendLine(string.Join(delimiter, output[index])); //File.WriteAllText(filePath, sb.ToString()); //comvert vsc to datatable var table = ConvertCSVtoDataTable("test.csv"); //get value of special column string[] columnName = { "Name", "Surname", "Age" }; for (int i = table.Columns.Count - 1; i >= 0; i--) { DataColumn dc = table.Columns[i]; if (!columnName.Contains(dc.ColumnName)) { table.Columns.Remove(dc); } } WriteDataToFile(table, "datatable.txt"); } public static DataTable ConvertCSVtoDataTable(string strFilePath) { StreamReader sr = new StreamReader(strFilePath); string[] headers = sr.ReadLine().Split(','); DataTable dt = new DataTable(); foreach (string header in headers) { dt.Columns.Add(header); } while (!sr.EndOfStream) { string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); DataRow dr = dt.NewRow(); for (int i = 0; i < headers.Length; i++) { dr[i] = rows[i]; } dt.Rows.Add(dr); } return dt; } public static void WriteDataToFile(DataTable submittedDataTable, string submittedFilePath) { int i = 0; StreamWriter sw = null; sw = new StreamWriter(submittedFilePath, false); for (i = 0; i < submittedDataTable.Columns.Count - 1; i++) { sw.Write(submittedDataTable.Columns[i].ColumnName + ";"); } sw.Write(submittedDataTable.Columns[i].ColumnName); sw.WriteLine(); foreach (DataRow row in submittedDataTable.Rows) { object[] array = row.ItemArray; for (i = 0; i < array.Length - 1; i++) { sw.Write(array[i].ToString() + ";"); } sw.Write(array[i].ToString()); sw.WriteLine(); } sw.Close(); } } }
Best Regards,
Wendy
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.- Edited by Wendy ZangMicrosoft contingent staff Thursday, September 6, 2018 6:56 AM
- Marked as answer by CanAcarDUS Friday, September 7, 2018 2:55 PM
Thursday, September 6, 2018 6:55 AM
All replies
-
You will need to call Flush and Close method on StreamWriter for it :
while ( ( currentLine = sr.ReadLine() ) != null ) { File.Write(currentLine); File.Flush(); }
File.Close();
or you will need to set AutoFlush property to true instead :
StreamWriter File = new StreamWriter("NewText.txt");
File.AutoFlush = true;
As it implements IDisposable, it's more better to use it with using block :
using (StreamWriter File = new StreamWriter("NewText.txt")) { while ( ( currentLine = sr.ReadLine() ) != null ) { File.Write(currentLine); File.Flush(); } }
You can also take a look at the following post that would be helpful too:
Hope it helps!
[If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click
"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]
Blog | LinkedIn | Stack Overflow | Facebook
- Edited by Ehsan Sajjad Tuesday, September 4, 2018 3:53 PM
- Proposed as answer by Ehsan Sajjad Tuesday, September 4, 2018 4:25 PM
Tuesday, September 4, 2018 3:46 PM -
Thank you so much, that helped me a lot to solve my problem. I learned a new thing with your help! I appreciate!
Could you also tell me how i can save single columns like: write only Name, Surname and Age Columns?
Wednesday, September 5, 2018 9:01 AM -
Hi CanAcarDUS,
Try the code below to get the single columns. You could set the column you want in columnName string array in the code.
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; using System.Diagnostics; using System.Diagnostics.Eventing.Reader; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using System.IO; using System.IO.Ports; using System.Linq; using System.Management; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; namespace ConsoleApp { public class Program { public static void Main(string[] args) { ////create a csv file //string filePath = @"test.csv"; //string delimiter = ","; //string[][] output = new string[][]{ // new string[]{"Name", "Surname", "Age","Date of Birth","Place"}, // new string[]{"Apple", "A", "10","1990/3/4","USA" }, // new string[]{"Bob", "B", "11","1991/3/4","China" }, // new string[]{"Cherry", "C", "12","1992/3/4","Japan" } // }; //int length = output.GetLength(0); //StringBuilder sb = new StringBuilder(); //for (int index = 0; index < length; index++) // sb.AppendLine(string.Join(delimiter, output[index])); //File.WriteAllText(filePath, sb.ToString()); //comvert vsc to datatable var table = ConvertCSVtoDataTable("test.csv"); //get value of special column string[] columnName = { "Name", "Surname", "Age" }; for (int i = table.Columns.Count - 1; i >= 0; i--) { DataColumn dc = table.Columns[i]; if (!columnName.Contains(dc.ColumnName)) { table.Columns.Remove(dc); } } WriteDataToFile(table, "datatable.txt"); } public static DataTable ConvertCSVtoDataTable(string strFilePath) { StreamReader sr = new StreamReader(strFilePath); string[] headers = sr.ReadLine().Split(','); DataTable dt = new DataTable(); foreach (string header in headers) { dt.Columns.Add(header); } while (!sr.EndOfStream) { string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); DataRow dr = dt.NewRow(); for (int i = 0; i < headers.Length; i++) { dr[i] = rows[i]; } dt.Rows.Add(dr); } return dt; } public static void WriteDataToFile(DataTable submittedDataTable, string submittedFilePath) { int i = 0; StreamWriter sw = null; sw = new StreamWriter(submittedFilePath, false); for (i = 0; i < submittedDataTable.Columns.Count - 1; i++) { sw.Write(submittedDataTable.Columns[i].ColumnName + ";"); } sw.Write(submittedDataTable.Columns[i].ColumnName); sw.WriteLine(); foreach (DataRow row in submittedDataTable.Rows) { object[] array = row.ItemArray; for (i = 0; i < array.Length - 1; i++) { sw.Write(array[i].ToString() + ";"); } sw.Write(array[i].ToString()); sw.WriteLine(); } sw.Close(); } } }
Best Regards,
Wendy
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.- Edited by Wendy ZangMicrosoft contingent staff Thursday, September 6, 2018 6:56 AM
- Marked as answer by CanAcarDUS Friday, September 7, 2018 2:55 PM
Thursday, September 6, 2018 6:55 AM -
You are amazing! Thank you so much!Friday, September 7, 2018 2:57 PM