编程语言
首页 > 编程语言> > 如何在C#中将csv分隔符从“,”更改为“:”

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

作者:互联网

我正在尝试通过读取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);
    }
}

现在,我想在输出文件中将定界符更改为“:”而不是“,”

我该怎么做?请帮我.

解决方法:

由于您正在尝试修改文本字符,因此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位等,具体取决于编码.流阅读器将为您处理.

标签:csv,console-application,c,net
来源: https://codeday.me/bug/20191119/2034157.html