首页 > 解决方案 > 当我不知道原始编码时如何在 c# 中将文件转换为 unix 或 windows

问题描述

在 c# 中,我有一个具有 Unix 行结尾(\r)的文件,我需要将其替换为 Windows(\r\n)。但,

1 - 我不知道原始文件编码(utf-8、unicode、iso8852-1 等)和

2 - 我不知道原始文件有多大。

第一点很重要——我不能简单地使用 StreamWriter 读写每一行,因为我不知道原始编码。

我怎样才能做到这一点?

标签: c#.net

解决方案


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


推荐阅读