如何在C#中将csv分隔符从“,”更改为“:”

时间:2016-01-12 23:49:06

标签: c# .net csv console-application

我正在尝试通过在C#控制台应用程序中读取现有的CSV文件来生成新的CSV文件。

using (FileStream stream = File.OpenRead("C:\\Files\\test_input_file.csv"))
using (FileStream writeStream = File.OpenWrite("C:\\Files\\test_Output_file.csv"))
{
    BinaryReader reader = new BinaryReader(stream);
    BinaryWriter writer = new BinaryWriter(writeStream);

    // create a buffer to hold the bytes 
    byte[] buffer = new Byte[1024];
    int bytesRead;

    // while the read method returns bytes
    // keep writing them to the output stream
    while ((bytesRead = stream.Read(buffer, 0, 1024)) > 0)
    {
        writeStream.Write(buffer, 0, bytesRead);
    }
}

现在我想在输出文件

中将分隔符更改为“:”而不是“,”

我该怎么办?请帮帮我。

2 个答案:

答案 0 :(得分:2)

因为您正在尝试修改文本字符,所以BinaryReader不适合您的案例。由于编码问题,您需要使用StreamReader。

using (FileStream stream = File.OpenRead("C:\\Files\\test_input_file.csv"))
using (FileStream writeStream = File.OpenWrite("C:\\Files\\test_Output_file.csv"))
{
    StreamReader reader = new StreamReader(stream);
    StreamWriter writer = new StreamWriter(writeStream, reader.CurrentEncoding);

    // create a buffer to hold the chars 
    char[] buffer = new char[1024];
    int charsRead;

    // while the read method returns chars
    // keep writing them to the output stream
    while ((charsRead =
            reader.Read(buffer, 0, buffer.Length)) > 0)
    {
        for (int i = 0; i < charsRead; i++)
        {
            if (buffer[i] == ':') buffer[i] = ',';
        }
        writer.Write(buffer, 0, charsRead);
    }
}

编码问题是什么?一个字符可以是1,2或3个字节,甚至是7位等...取决于编码。流阅读器将为您处理此事。

答案 1 :(得分:1)

假设:

  • 您的CSV文件以ASCII或UTF-8
  • 编码
  • 您的CSV值不会包含任何嵌入的逗号

...你可以简单地使用:

for (int i = 0; i < bytesRead; i++)
    if (buffer[i] == ',')
        buffer[i] = ':';

writeStream.Write(buffer, 0, bytesRead);