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

标签 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);
    }
}

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

我该怎么做?请帮助我。

最佳答案

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

关于c# - 如何在 C# 中将 csv 分隔符从 ","更改为 ": ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34755949/

相关文章:

c# - 部署 asp.net web 应用程序时出现问题

c# - 从 C# 分配一个 javascript 变量

c# - .NET:DDD 和 ASMX,避免在代理类上使用多个命名空间

c# - 将换行符附加到字符串的最佳方法,最后一个除外

c# - 如果我有 _full_ 绝对 uri,如何获取对 Azure blob/文件的 GetFileReference?

c# - 什么会导致不为 UDP 数据报计算 IP header 校验和?

python - 读取每个文件后如何写入新行?

C# 串行接收限制

php - 从逗号分隔的字符串中删除重复项

csv - 该查询的执行计划包含 Eager 运算符,该运算符强制所有相关数据在继续之前在主内存中具体化