如何在不合并先前值的情况下附加CSV文件 [英] How to Append CSV file without merging the previous values

查看:70
本文介绍了如何在不合并先前值的情况下附加CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码,用于将列表元素转换为CSV文件。

它工作正常。

但事实是,在附加新数据时,最后一个元素CSV中先前数据的连接与新形成的数据连接。



这是我的代码。请在新行中分隔数据



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

TextWriter writer = new StreamWriter(fileName, true );

List< string> stringList = new List< string>();
Console.Write( 输入列表中元素的数量:);
int listSize;
int .TryParse(Console.ReadLine(), out listSize);
Console.WriteLine( 逐个输入{0}个元素:,listSize) ;
for int index = 0 ; index < listSize; index ++)
{
stringList.Add(Console.ReadLine());
}
Console.Write( \ nList元素:\ n \ n );
foreach var items in stringList)
{
Console.WriteLine(items);
}
string csvString = string .Join( ,stringList.ToArray());
Console.WriteLine( \ nCSV输出);
Console.WriteLine( \ n + csvString);
writer.Write(csvString);
writer.Close();
Console.ReadLine();

解决方案

通过更改writer.Write(csvString)

to WriteLine(csvString)如下面的代码所示,我们可以避免这个问题



 writer.WriteLine(csvString); 


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

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();

解决方案

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

writer.WriteLine(csvString);


这篇关于如何在不合并先前值的情况下附加CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆