如何在C#中将CSV分隔符从","更改为":"

3
我正在尝试在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);
    }
}

现在我想在输出文件中使用“:”作为分隔符,而不是“,”。

我该怎么做呢?请帮帮我。


1
你需要使用StreamReader而不是BinaryReader来解决编码问题。它是逐个字符读取的。然后,简单地将:字符更改为,。请注意,您还需要StreamWriter。 - M.kazem Akhgary
我是C#的新手..你能建议我在哪里使用流写入器吗? - bhavya158
2个回答

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
假设以下内容成立:
  • 你的CSV文件采用ASCII或UTF-8编码
  • 你的CSV值不包含任何嵌入逗号

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

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

writeStream.Write(buffer, 0, bytesRead);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接