开发者

How to read values from a comma separated file?

开发者 https://www.devze.com 2023-04-05 04:06 出处:网络
I want to read words in a text file of a line separated by commas in c sharp. For example, I want to read this line:

I want to read words in a text file of a line separated by commas in c sharp.

For example, I want to read this line:

9/10/2011 10:05,995.4,998.8,995.4,997.5,118000

and get the values: 9/10/2011 10:05, 995.4, 998.8, 995.4, 997.5 and 118000.

Next, I also need to change the format of the date to MMddYYYY, and of the time to HHmmss (e.g. 100500).

I am using this code for reading is there anything wrong

 private void button1_Click(object sender, EventArgs e)
 {
     StreamReader reader1 = File.OpenText(Path1);
     string 开发者_高级运维str = reader1.ReadToEnd();
     reader1.Close();
     reader1.Dispose();
     //     File.Delete(Path1);

     string[] Strarray = str.Split(new char[] { Strings.ChrW(7) });
     int abc = Strarray.Length - 1;
     int xyz = 0;
     bool status = true;

     while (xyz <= abc)
     {
        try
        {
           status = true;
           string[] strarray1 = Strarray[xyz].Split(",".ToCharArray());
           string SecName = strarray1[0];
           int a2 = 0;
           while (status)  //If the selected list is empty or the text file has selected name this will execute
           {
              status = false;
              string SecSym = strarray1[1];
              int DT = int.Parse(strarray1[2]);
              int TM = int.Parse(strarray1[3]);
              float O = float.Parse(strarray1[2]);
              float H = float.Parse(strarray1[3]);
              float L = float.Parse(strarray1[4]);
              float C = float.Parse(strarray1[5]);
              double OI = double.Parse(Convert.ToString(0));
              float V = float.Parse(strarray1[6]);

              //   string a = string.Concat(SecName, ",",SecSym,",", DT, ",", TM, ",", O, ",", H, ",", L);
              //writer.WriteLine(a);
           }
        }
        catch
        { }
     }
   }
}


.Net comes with a ready CSV parser you can use to get your data. It's a part of VB.net, but you can easily use it in C# by adding a reference to the assembly Microsoft.VisualBasic (it's OK, honesly), and a using statement: using Microsoft.VisualBasic.FileIO;.

The code should be simple to understand:

List<String[]> fileContent = new List<string[]>();

using(FileStream reader = File.OpenRead(@"data.csv")) // mind the encoding - UTF8
using(TextFieldParser parser = new TextFieldParser(reader))
{
    parser.TrimWhiteSpace = true; // if you want
    parser.Delimiters = new[] { "," };
    parser.HasFieldsEnclosedInQuotes = true; 
    while (!parser.EndOfData)
    {
        string[] line = parser.ReadFields();
        fileContent.Add(line);
    }
}

CSV is fairly simple, but it may contain quoted values with commas and newlines, so using Split isn't the best option.


Use the String.Split method to get an array of strings:

string[] ar = line.Split(',')


This should get you started.

using System;
using System.IO;

public class Sample
{
    public static void Main() {
        using (StreamReader reader = new StreamReader("yourfile.txt")) {
            string line = null;
            while (null != (line = reader.ReadLine())) {
                string[] values = line.Split(',');
                DateTime date = DateTime.Parse(values[0];
                float[] numbers = new float[values.Length - 1];
                for (int i = 1; i < values.Length - 1; i++)
                    numbers[i - 1] = float.Parse(values[i]);

                // do stuff with date and numbers
            }
        }
    }
}

I have also posted a simple CsvReader class which may be helpful for you.


For a quick and simple solution, you can stream through the file and parse each line using String.Split like this:

using (var sr = File.OpenText("myfile.csv"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        var fields = line.Split(',');
        var date = DateTime.Parse(fields[0].Trim());
        var value1 = fields[0].Trim();
    }
}

However, this appraoch if fairly error prone, for a more robust solution check out the CsvReader project, it's excellent for parsing CSV files like this. It will handle field values with commas, trimming spaces before and after fields, and much more.

If you need to parse a date string from a format not recognised by DateTime.Parse, try using DateTime.ParseExact instead.


For 1st part of your task use Split method with , as separator. To convert string datetime from one format to another you need to convert that string to datetime(DateTime.Parse, DateTime.ParseExact) and then convert to final format using DateTime.ToString method.


rows contain your output

   StreamReader sStreamReader = new StreamReader("File Path");
    string AllData = sStreamReader.ReadToEnd();
    string[] rows = AllData.Split(",".ToCharArray());
0

精彩评论

暂无评论...
验证码 换一张
取 消