0

I want to extract values of a variable in CSV file from a c# console application.

Variable has unlimited values like it is the position value from a stream when the stream ends variable values also finishes. I have seen many examples on the internet but none of them answers my question.

Here is what I found.

var file = @"C:\SavedBTData.csv";

using (var stream = File.AppendText(file))
{
    for (int i = 0; i < ToBT.Count(); i++)
    {
        BTdata[i] = ToBT[i].ToString();

    }
    string csvRow = string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", BTdata[0], BTdata[1], BTdata[2], BTdata[3], BTdata[4], BTdata[5], BTdata[6], BTdata[7]);

    stream.WriteLine(csvRow);
}

But here in string csvRow line .... I don't know how much values I get from that variable moreover I have to save data in just 1 column.

Anyone with a possible suggestion.

Backs
  • 24,430
  • 5
  • 58
  • 85
leo90
  • 99
  • 1
  • 2
  • 8
  • https://stackoverflow.com/questions/17353454/csvhelper-read-in-multiple-columns-to-a-single-list – xdtTransform Jan 09 '19 at 09:40
  • I will recommend using any avaidable Library to map your CSV. and not hand writing the parser again and again. Define your Csv. Beeing square on the input definition will save you a lot of trouble! – xdtTransform Jan 09 '19 at 09:44
  • Dont write your own parser if possible. I use https://www.filehelpers.net/ for CSV operations. – bic Jan 09 '19 at 09:54

2 Answers2

2

Use String.Join method to combine all values of array:

string csvRow = string.Join(",", BTdata);

Also, you do not need to convert all to string:

string csvRow = string.Join(",", ToBT);
Backs
  • 24,430
  • 5
  • 58
  • 85
  • Moreover, if I have a variable which has values of a sensor I want whenever that variable gets new value then that should be added in csv file column and so on. – leo90 Jan 09 '19 at 10:01
0
       var file = @"D:\\awaisFile.csv";
        using (var stream = File.AppendText(file))
        {
            /* initialize elements of array n */
            for (i = 0; i < num1.Count(); i++)
            {
                Console.Write("Enter value of 'num1'");
                Console.WriteLine(i + 1);
                num1[i] = int.Parse(Console.ReadLine());
                temp1[i] = num1[i].ToString();

                Console.Write("Enter value of 'num2'");
                Console.WriteLine(i + 1);
                num2[i] = int.Parse(Console.ReadLine());
                temp2[i] = num2[i].ToString();

                res[i] = multiplyNum(num1[i], num2[i]);

                Console.WriteLine("Element1[{0}] = {1}", i, res[i]);
                temp3[i] = res[i].ToString();

                string csvRow = string.Format("{0},{1},{2}", temp1[i], temp2[i], temp3[i]);

                stream.WriteLine(csvRow);

            }

        }

I used this way and it worked fine for me.

leo90
  • 99
  • 1
  • 2
  • 8