在 C# 中将文件中的行尾从 DOS 格式转换为 UNIX 格式 [英] Converting the line endings in a file from DOS to UNIX format in C#

查看:43
本文介绍了在 C# 中将文件中的行尾从 DOS 格式转换为 UNIX 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件中的行尾从 DOS 格式转换为 C# 中的 Unix 格式.

I would like to convert the line endings in a file from DOS format to Unix format in C#.

Unix 系统使用换行符 (LF) 作为行分隔符.唯一值得注意的例外是 Microsoft Windows,它使用回车符后跟换行符 (CRLF).

Unix systems use the linefeed character (LF) as a line separator. The only notable exception is Microsoft Windows, which uses a carriage return followed by a linefeed (CRLF).

如何使用 C# 将文件中的行尾从 DOS 更改为 Unix 格式.需要一些有关转换的指导.

How do I change the line endings in a file from DOS to Unix Format using C#. Need some guidance on converting this.

推荐答案

这是你的答案 将文件从 Dos 转换到 Unix 并返回:

private void Dos2Unix(string fileName)
{
    const byte CR = 0x0D;
    const byte LF = 0x0A;
    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, CR, position);
            if ((index >= 0) && (data[index + 1] == LF))
            {
                // Write before the CR
                bw.Write(data, position, index - position);
                // from LF
                position = index + 1;
            }
        }
        while (index >= 0);
        bw.Write(data, position, data.Length - position);
        fileStream.SetLength(fileStream.Position);
    }
}

这篇关于在 C# 中将文件中的行尾从 DOS 格式转换为 UNIX 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆