c# - 当我不知道原始编码时如何在 c# 中将文件转换为 unix 或 windows
问题描述
在 c# 中,我有一个具有 Unix 行结尾(\r)的文件,我需要将其替换为 Windows(\r\n)。但,
1 - 我不知道原始文件编码(utf-8、unicode、iso8852-1 等)和
2 - 我不知道原始文件有多大。
第一点很重要——我不能简单地使用 StreamWriter 读写每一行,因为我不知道原始编码。
我怎样才能做到这一点?
解决方案
private void Unix2Dos(string fileName)
{
const byte CR = 0x0D;
const byte LF = 0x0A;
byte[] DOS_LINE_ENDING = new byte[] { CR, LF };
byte[] data = File.ReadAllBytes(fileName);
using (FileStream fileStream = File.OpenWrite(fileName))
{
BinaryWriter bw = new BinaryWriter(fileStream);
int position = 0;
int index = 0;
do
{
index = Array.IndexOf<byte>(data, LF, position);
if (index >= 0)
{
if ( ( index > 0 ) && (data[index - 1] == CR ))
{
// already dos ending
bw.Write(data, position, index - position + 1);
}
else
{
bw.Write(data, position, index - position);
bw.Write(DOS_LINE_ENDING);
}
position = index + 1;
}
}
while (index > 0);
bw.Write(data, position, data.Length - position);
fileStream.SetLength(fileStream.Position);
}
}
参考:http ://csharp-goodies.blogspot.com/2011/02/convert-files-from-dos-to-unix-and-back.html
推荐阅读
- knockout.js - 为什么在表行中使用 data-bind ='if' 时会出现 Knockout js 的 ReferenceError
- amazon-web-services - AWS Kinesis 流检查点
- spring-boot - 无法在启用动态端口的 AWS ECS 上正确注册 Eureka 服务
- spring-boot - Spring Boot 不在 Azure WebApp 和 Skype 上显示机器人响应
- java - Java SWT:22 MB 的 runnable.jar 文件。可以减小尺寸吗?
- rest - 使用 Lumen 和 NeoEloquent OGM 从 Neo4j 检索 DateTime
- azure-resource-manager - 资源未定义
- laravel - 使用 JavaScript 查看 laravel 会话
- sql - 在特定列上按标题计数
- reactjs - Express 和 React,package.json 中的代理在 dev 中工作,但为什么它在生产中与 heroku 一起工作?