0

I tried to export an 2-D array from c# to a csv file but last several rows are missing in the csv file.I don't know where the problem is in my code.

First,I'd like to know if my code is not correct?

Second,is it possible to add a title for each row in the csv file .

Thanks in advance

Here is an example of my array in c#

 string[,] array=new string[]{{2000,2},{2001,4}}

I want to a result like this in csv file with title

  Date   C1
  2000   2
  2001   4

My code:

 var outfile=new.streamwriter(@"fileadress.csv");
 for(int i=0;i<array.GetUpperbound(0);i++)
 {
   string content="";
  for(int j=0;j<array.GetUpperbound(1);j++)
   {
     content+= array[i,j]+";";
   }
  outfile.WriteLine(content);

 }
2
  • StreamWriters are IDisposable, so you should Dispose() them when you've finished... Commented Jul 25, 2015 at 20:08
  • also your example is not valid C# as is Commented Jul 25, 2015 at 20:13

1 Answer 1

1

There are a lot of problems in the code shown. The most important is the wrong usage of GetUpperBound that return the 'upperbound' of your array, and your example this upperbound is 1 (not 2) thus the < array.UpperBound skips the last position in the array.

I suggest a reworking of your code in this way

// This is an array of strings right?
string[,] array=new string[,]{{"2000","2"},{"2001","4"}};

// Use a StringBuilder to accumulate your output
StringBuilder sb = new StringBuilder("Date;C1\r\n");
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
    for (int j = 0; j <= array.GetUpperBound(1); j++)
    {
         sb.Append((j==0 ? "" : ";") + array[i, j]);        
    }
    sb.AppendLine();
}

// Write everything with a single command 
File.WriteAllText(@"fileadress.csv", sb.ToString());
Sign up to request clarification or add additional context in comments.

3 Comments

File.WriteAllText(@"fileadress.csv", sb.ToString());
Yes, changed it, could you refresh the answer?
I tested it in my program. But it says file doesn't exist. I'd like to ask you this question,but then i found out i missed using System.IO. my comment is a mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.