Click here to Skip to main content
15,900,108 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
I have written a code for converting list elements to CSV file.
It works fine.
But the thing is that while appending with then new datas the last element of the previous data in the CSV gets concatenated with the newly formed datas.

Here is my code. Please separate the datas in a new line

C#
string fileName = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\CSV.csv";

            TextWriter writer = new StreamWriter(fileName,true);
          
            List<string> stringList = new List<string>();
            Console.Write("Enter the number of elements in the list: ");
            int listSize;
            int.TryParse(Console.ReadLine(),out listSize);
            Console.WriteLine("Enter {0} elements one by one: ",listSize); 
            for (int index = 0; index < listSize; index++)
            {
                stringList.Add(Console.ReadLine());
            }
            Console.Write("\nList elements:\n\n");
            foreach (var items in stringList)
            {
                Console.WriteLine(items);
            }
            string csvString = string.Join(",", stringList.ToArray());
            Console.WriteLine("\nCSV Output");
            Console.WriteLine("\n"+csvString);
            writer.Write(csvString);
            writer.Close();
            Console.ReadLine();
Posted
Updated 18-Feb-14 2:06am
v2
Comments
ZurdoDev 18-Feb-14 7:08am    
Just add a new line in yourself. Where are you stuck?
KUMAR619 18-Feb-14 7:56am    
@ RyanDev
I have found the solution


writer.WriteLine(csvString);
does the work.

Thanks for answering
ZurdoDev 18-Feb-14 7:57am    
Sure. You should post as solution so it no longer shows as unanswered.
KUMAR619 18-Feb-14 8:08am    
@RyanDev Thanks
Sergey Alexandrovich Kryukov 19-Feb-14 17:19pm    
Would you please stop flooding this forum with your fake questions and "answers". Why do you think that anyone is interested to know how you make bugs and then fix them?
And that fact that you even self-accept such "answers" is just cheating. Why?
—SA

1 solution

By changing writer.Write(csvString)
to WriteLine(csvString) as shown in the code below we can avoid this problem

C#
writer.WriteLine(csvString);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900