【问题标题】:C# File.ReadAllLines not breaking on line feedsC# File.ReadAllLines 不中断换行
【发布时间】:2010-05-06 01:46:57
【问题描述】:

我正在构建一个需要修改配置文件的应用程序。

我的问题是我无法逐行读取文件。我一直把整个文件当作一个字符串。

string ConfigTemplate = AEBuildsSPFolderName + "\\Template_BuildReleaseScript.Config";

string[] fileSourceLines = File.ReadAllLines(ConfigTemplate, Encoding.Default);
//Returns the entire file contents into the first array element.

using (StreamReader reader = new StreamReader(ConfigTemplate))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
//Returns the entire file contents into the first line read.

知道我做错了什么吗?

谢谢,

大卫

【问题讨论】:

    标签: c# .net file-io


    【解决方案1】:

    我猜使用的换行符可能不是\r\n

    当您将整个文件读入单个字符串时,请尝试调用 yourString.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); 看看是否适合您。

    另外,由于ReadAllLines() 只是读取单个字符串,您可以简单地使用ReadAllText()

    【讨论】:

    • 感谢您的回复。根据您的 cmets,这是我放在一起的测试代码段... //Get File Lines string[] fileSourceLines = File.ReadAllLines(ConfigTemplate, Encoding.Default); if (fileSourceLines.Length == 1) { string yourString = fileSourceLines[0]; string[] newSourceLines = yourString.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); //这个数组仍然只包含1​​个字符串。 } newSourceLines 数组仍然只包含 1 个字符串。任何其他建议:) 谢谢,大卫
    【解决方案2】:

    您的文件可能使用\n 字符(没有\r)作为换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 2014-08-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 2017-04-30
      相关资源
      最近更新 更多