gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:04:39 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com