none
c# RRS feed

  • Question

  • I want to import .csv files data to c#, visual studio by date range and time range how i can code for it. i am also using a link list "set data source", so how can do it for it. i couldn't able to upload the pictures,

    I am using visual studio 2019 and c# language.




    Thursday, August 15, 2019 4:17 AM

All replies

  • Not sure about what you mean with date- and time-range. But you can get a list of csv files from a named direcory (C:\temp\ in this case) and than check the creation date (or some other date infomation available in System.IO.FileInfo):

    foreach (var fi in new DirectoryInfo(@"C:\Temp\").GetFiles("*.csv"))
    {
        if (fi.CreationTime > DateTime.Now.AddDays(-1))
        {
            CSVimport(String.Empty);
        }
    }
    

    And each selected file can be imported using the Microsoft.VisualBasic.FileIO namespace (don't get confused by the VB in namespace; you can still use c# here):

    // reference Microsoft.VisualBasic.dll for this
    using Microsoft.VisualBasic.FileIO;
    
    public void CSVimport(String filename)
    {
        using(var rdr = new TextFieldParser(filename))
        {
            rdr.SetDelimiters(new String[] {","});
            while(!rdr.EndOfData)
            {
                var fields = rdr.ReadFields();
                // Do Stuff
            }
        }
    }
    

    Thursday, August 15, 2019 5:49 AM
  • Hi tharminianandasivanesan,

    Thank you for posting here.

    For your question, you want to import csv file by using c#.

    You could try the following code.

     using (TextFieldParser parser = new TextFieldParser(@"test.csv"))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    while (!parser.EndOfData)
                    {
                        string[] fields = parser.ReadFields();
                        foreach (string field in fields)
                        {
                            Console.WriteLine(field);
                        }
                        Console.WriteLine("****");
                    }
                }

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 5:51 AM
    Moderator
  • Ok Sir, But i am not using visual basic and i am using c# language
    Thursday, August 15, 2019 5:51 AM
  • Hi 

    >>Ok Sir, But i am not using visual basic and i am using c# language

    This is c# language, only adding a reference Microsoft.VisualBasic.dll.

    Best Regards,

    Jack



    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.

    Thursday, August 15, 2019 5:55 AM
    Moderator
  • i am using link label to get data how can use it and i am using class regarding csv data, below are my class.cs and link label code

    //This is the class used to parse the excel ".csv" to dataGridView
    
            /// <summary>
            /// Open the CSV file via a fixed string or use a opn file dialog
            /// </summary>
            /// <param name="filePath"></param>
            /// <returns></returns>
            public static Task<DataTable> CopyCsvToDataTable(string filePath)
            {
                return Task.Run<DataTable>(() => {
    
                    if (!File.Exists(filePath))
                        throw new ArgumentException("File does not exist in the selected path.");
                    StreamReader sr = new StreamReader(filePath);
                    string[] headers = sr.ReadLine().Split(',');
                    var 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++)
                        {
                            if (rows.Length <= i)
                                continue;
                            dr[i] = rows[i];
                        }
                        dt.Rows.Add(dr);
                    }
                    return dt;
                });
    
            }
            private async void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
            {
                filePath = "";
    
                OpenFileDialog op = new OpenFileDialog();
                op.Filter = "CSV File (*.csv)|*.csv";
                op.InitialDirectory = @"D:\";
                op.Title = "Please select the path of the CSV file";
                linkLabel1.Enabled = false;
                btnSearch.Enabled = false;
                btnPrint.Enabled = false;
                Cursor.Current = Cursors.WaitCursor;
                if (op.ShowDialog() == DialogResult.OK)
                {
                    filePath = op.FileName;
    
                    bs.Clear();
                    var tgs = await SearchCSV();
                    foreach (var gts in tgs)
                        bs.Add(gts);
    
    
                    linkLabel1.Enabled = true;
                    btnSearch.Enabled = true;
                    btnPrint.Enabled = true;
                    Cursor.Current = Cursors.Default;
                }
            }



          

    Thursday, August 15, 2019 6:11 AM
  • Hi 

    Thanks for the feedback.

    I tested the code you provided, it works well. If you want to parse the excel ".csv" to dataGridView, you could use the following code to solve the problem.

     private void Form1_Load(object sender, EventArgs e)
            {
                var m = CopyCsvToDataTable(@"D:\t\Book1.csv");
                DataTable dt = m.Result;
                dataGridView1.DataSource = dt;
               
            }
            public static Task<DataTable> CopyCsvToDataTable(string filePath)
            {
                return Task.Run<DataTable>(() => {
    
                    if (!File.Exists(filePath))
                        throw new ArgumentException("File does not exist in the selected path.");
                    StreamReader sr = new StreamReader(filePath);
                    string[] headers = sr.ReadLine().Split(',');
                    var 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++)
                        {
                            if (rows.Length <= i)
                                continue;
                            dr[i] = rows[i];
                        }
                        dt.Rows.Add(dr);
                    }
                    return dt;
                });
    
            }

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 6:25 AM
    Moderator
  • where should i apply this code sir

    Thursday, August 15, 2019 6:33 AM
  • Hi

    >>where should i apply this code sir

    I am not sure what you mean?  The code is applied in windows form app.

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 6:35 AM
    Moderator
  • but i am putting the above my code in a class that data table part so now should i put this in windows form application i want to select the csv while program is running that why i use the link label i have according to link label
    Thursday, August 15, 2019 6:45 AM
  • Hi

    Could you tell you what is used for link label? Besides, please describe it more clearly, which will help us to solve your problem better.

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 6:56 AM
    Moderator
  • my interface is like start date end date start time and end time and a link label which will choose the csv file from file explorer (like New Volume (D):) here we give only the main path while program running i have to the csv file from path which i have given and have to do search
    Thursday, August 15, 2019 7:30 AM
  • Hi

    Thanks for the feedback.

    You could use the following code to make this operations.

     public static Task<DataTable> CopyCsvToDataTable(string filePath)
            {
                return Task.Run<DataTable>(() => {
    
                    if (!File.Exists(filePath))
                        throw new ArgumentException("File does not exist in the selected path.");
                    StreamReader sr = new StreamReader(filePath);
                    string[] headers = sr.ReadLine().Split(',');
                    var 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++)
                        {
                            if (rows.Length <= i)
                                continue;
                            dr[i] = rows[i];
                        }
                        dt.Rows.Add(dr);
                    }
                    return dt;
                });
    
            }
            public string filepath { get; set; }
            private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
            {
                
                OpenFileDialog op = new OpenFileDialog();
                op.Filter = "CSV File (*.csv)|*.csv";
                op.InitialDirectory = @"D:\";
                op.Title = "Please select the path of the CSV file";
                linkLabel1.Enabled = false;
                //btnSearch.Enabled = false;
                //btnPrint.Enabled = false;
                Cursor.Current = Cursors.WaitCursor;
                if (op.ShowDialog() == DialogResult.OK)
                {
                    filepath = op.FileName;
                    var m = CopyCsvToDataTable(filepath);
                    DataTable dt = m.Result;
                    dataGridView1.DataSource = dt;
                }
            }

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 8:58 AM
    Moderator
  • thank you sir its worked very well and how can i code for get data by start date and end date start time and end time
    Thursday, August 15, 2019 9:00 AM
  • Hi 

    >>get data by start date and end date start time and end time

    I want to know if the data comes from csv.

    Could you give me a csv file example?

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 9:04 AM
    Moderator
  • i am getting data from csv file directly but can i add/link the csv file here sir

    Thursday, August 15, 2019 9:09 AM
  • Hi 

    Thanks for the feedback.

    First, you could try to add two dateTimePicker control.

    Then, please try the following code.

     public static Task<DataTable> CopyCsvToDataTable(string filePath)
            {
                return Task.Run<DataTable>(() => {
    
                    if (!File.Exists(filePath))
                        throw new ArgumentException("File does not exist in the selected path.");
                    StreamReader sr = new StreamReader(filePath);
                    string[] headers = sr.ReadLine().Split(',');
                    var 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++)
                        {
                            if (rows.Length <= i)
                                continue;
                            dr[i] = rows[i];
                        }
                        dt.Rows.Add(dr);
                    }
                    return dt;
                });
    
            }
            public string filepath { get; set; }
            private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
            {
                
                OpenFileDialog op = new OpenFileDialog();
                op.Filter = "CSV File (*.csv)|*.csv";
                op.InitialDirectory = @"D:\";
                op.Title = "Please select the path of the CSV file";
                linkLabel1.Enabled = false;
                Cursor.Current = Cursors.WaitCursor;
                if (op.ShowDialog() == DialogResult.OK)
                {
                    filepath = op.FileName;
                    var m = CopyCsvToDataTable(filepath);
                    DataTable dt = m.Result;
                    foreach (DataRow item in dt.Rows)
                    {
                        DateTime time = Convert.ToDateTime(item["date"]);
                        if(time>dateTimePicker1.Value&&time<dateTimePicker2.Value)
                        {
                            MessageBox.Show(time.ToString());
                        }
                    }
    
    
                }
            }

    Result:

    Csv file:

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 9:27 AM
    Moderator
  • i want to fetch data separately start date & start time and end date & end time like this

    
    Date  Time  L1  L2  L3  L12  L23  L31  I1  I2  I3  Frq1  Frq2  Frq3  PF1  PF2  PF3  kW  kVA  kVAr  kWh  kVArh  kVAh  thdV1%  thdV2%  thdV3%
    6/24/2019 0:00:00 235.21 0 0 235.13 0 235.15 0 0 0 50.25 0 0 1 1 1 0 0 0 0 0 0 6.66 0 0
    6/24/2019 0:00:02 235.21 0 0 235.13 0 235.15 0 0 0 50.25 0 0 1 1 1 0 0 0 0 0 0 4.44 0 0
    6/24/2019 0:00:06 235.21 0 0 235.13 0 235.15 0 0 0 50.25 0 0 1 1 1 0 0 0 0 0 0 6.69 0 0
    6/24/2019 0:00:10 235.21 0 0 235.13 0 235.15 0 0 0 50.25 0 0 1 1 1 0 0 0 0 0 0 6.69 0 0
    6/24/2019 0:00:15 235.21 0 0 235.13 0 235.15 0 0 0 50.25 0 0 1 1 1 0 0 0 0 0 0 5.78 0 0
    6/24/2019 0:00:19 235.21 0 0 235.13 0 235.15 0 0 0 50.25 0 0 1 1 1 0 0 0 0 0 0 5.78 0 0


    Thursday, August 15, 2019 9:35 AM
  • Hi 

    Thanks for the feedback.

    I want to know where you want to store these data, just read or store it into datagridview?

    Best Regards,

    Jack


    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.

    Thursday, August 15, 2019 9:49 AM
    Moderator
  • just to keep in datagridview and print all data (save to PDF format) that's all
    Thursday, August 15, 2019 9:51 AM
  • Ok Sir, But i am not using visual basic and i am using c# language

    If you want to to be precise - and as a programmer you must - you are using English language - I didn't any C# or VB in your posts.

    And from your description I can't understand with what you try to work - with files itself or with content in the files.


    Sincerely, Highly skilled coding monkey.

    Thursday, August 15, 2019 10:00 AM