编写c#程序结果为CSV文件

本文关键字:CSV 文件 结果 程序 编写 | 更新日期: 2023-09-27 18:02:34

我有一个c#程序,比较2个数据库表,并将结果上传到数据库中的另一个表。我开始得到一个maxpackets错误,我的理解是上传的结果太大了。

我的想法是转储结果到csv文件而不是。我试着遵循几个例子,但我的程序现在只是停滞不前。我哪里错了?

{
                string filePath = @"C:'users'rena'documents'test.csv";
                string delimiter = ",";
                string[][] output = new string[][]
                {
                    new string[] { "col 1 row 1", "col 2 row 1", "col 3 row 1"},
                    new string[] {"col 1 row 2", "col 2 row 2", "col 3 row 2"}
                };
                int length = output.GetLength(0);
                StringBuilder sb = new StringBuilder();
                for (int index = 0; index < length; index++)
                    sb.AppendLine(string.Join(delimiter, output[index]));
                if (!File.Exists(filePath))
                File.WriteAllText (filePath, sb.ToString())
            }

谢谢! !

编写c#程序结果为CSV文件

您可以尝试使用缓冲流进行编写。看看这是否更清楚:

void Main()
{
    string filePath = @"c:'temp'test.csv";
    string delimiter = ",";
    string[][] output = new string[][]
    {
        new string[] { "col 1 row 1", "col 2 row 1", "col 3 row 1"},
        new string[] {"col 1 row 2", "col 2 row 2", "col 3 row 2"}
        //tried with 2k here
    };
    int length = output.GetLength(0);
    StringBuilder sb = new StringBuilder();

    using (FileStream fileStream = File.Create(filePath))
    {
        using (BufferedStream bufferedStream = new BufferedStream(fileStream))
        {
            using (StreamWriter streamWriter = new StreamWriter(bufferedStream))
            {
                for (int index = 0; index < length; index++)
                    streamWriter.WriteLine(string.Join(delimiter, output[index]));
            }   
        }
    }
    if (!File.Exists(filePath))
    File.WriteAllText (filePath, sb.ToString());
}