从字符串数组创建CSV文件

use*_*861 -2 c# csv arrays export-to-csv

我试图将数据从对象列表导出到csv文件.我设法创建文件并创建第一行,但是我需要为每个循环创建一些循环来遍历每个对象.

这是我的代码:

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";

if (!File.Exists(filePath))
{
    File.Create(filePath).Close();
}

string delimter = ",";
string[][] output = new string[][] { 
  new string[] {"TEST1","TEST2"} 
};

int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();

for (int index = 0; index < length; index++)
{
    sb.AppendLine(string.Join(delimter, output[index]));
    File.AppendAllText(filePath, sb.ToString());
}
Run Code Online (Sandbox Code Playgroud)

有没有办法创建此文件并使用循环遍历所有对象并将其显示在文件中.

小智 17

这是解决方案:

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";

if (!File.Exists(filePath))
{
    File.Create(filePath).Close();
}
string delimter = ",";
List<string[]> output = new List<string[]>();

//flexible part ... add as many object as you want based on your app logic
output.Add(new string[] {"TEST1","TEST2"});
output.Add(new string[] {"TEST3","TEST4"});

int length = output.Count;

using (System.IO.TextWriter writer = File.CreateText(filePath))
{
    for (int index = 0; index < length; index++)
    {
        writer.WriteLine(string.Join(delimter, output[index]));
    }
}
Run Code Online (Sandbox Code Playgroud)


Dal*_*las 5

假设obj是一个String列表我通常使用它

System.IO.File.WriteAllLines(stringFilePath, obj.ToArray());
Run Code Online (Sandbox Code Playgroud)