如何将回车转换为实际的换行符

时间:2016-06-21 21:15:22

标签: c# text replace line-breaks

我有一个我从this下载的文本文件(它只是英文词典),它在浏览器中显示正常,但是当我在记事本中打开它时,它没有识别出来换行。我认为一个简单的C#应用​​程序可以检测它们使用的回车的味道,并将它们转换为实际的换行符并吐出更好的格式化的txt文件,但是我认为String.Replace("\r", "\n");这样的技术失败了很简单。如何对这些回车进行编码,如何重新格式化文件以使其在记事本中可读? C#是首选,因为这是我以前所使用的,但如果它在其他方法中更容易,我会很乐意考虑替代方案。

2 个答案:

答案 0 :(得分:2)

如果你真的想在c#中这样做,你需要做的就是这个......

File.WriteAllLines("outfile.txt", File.ReadAllLines("infile.txt"));

...如果你想要稍微复杂一点但速度更快,内存更少,那就这样做......

using (var reader = new StreamReader("infile.txt"))
using (var writer = new StreamWriter("outfile.txt"))
    while (!reader.EndOfStream)
        writer.WriteLine(reader.ReadLine());

...如果你真的想过度使用它作为使用扩展方法和LINQ的借口那么就这样做......

//Sample use
//"infile.txt".ReadFileAsLines()
//            .WriteAsLinesTo("outfile.txt");
public static class ToolKit
{
    public static IEnumerable<string> ReadFileAsLines(this string infile)
    {
        if (string.IsNullOrEmpty(infile))
            throw new ArgumentNullException("infile");
        if (!File.Exists(infile))
            throw new FileNotFoundException("File Not Found", infile);

        using (var reader = new StreamReader(infile))
            while (!reader.EndOfStream)
                yield return reader.ReadLine();
    }
    public static void WriteAsLinesTo(this IEnumerable<string> lines, string outfile)
    {
        if (lines == null)
            throw new ArgumentNullException("lines");
        if (string.IsNullOrEmpty(outfile))
            throw new ArgumentNullException("outfile");

        using (var writer = new StreamWriter(outfile))
            foreach (var line in lines)
                writer.WriteLine(line);
    }
}

答案 1 :(得分:1)

记事本是我所知道的唯一一个Windows文本编辑器,它不能识别Unix风格的换行符\n,并且需要Windows样式的换行符\r\n才能正确格式化文本。如果您将\n转换为\r\n,则会按预期显示。此外,任何其他(现代)文本编辑器都应该按原样正确显示文本。

相关问题