Stream Reader Readline detect newline characters

一世执手 提交于 2019-12-02 08:12:47
sr.ReadLine().Replace(Environment.NewLine, String.Empty);

EDIT: In case the end of line is not \r\n but \n you can use regex:

Line = Regex.Replace(sr.ReadLine(), @"(\r\n|\n)", String.Empty);

The call to Replace isn't working because of this detail from the MSDN doc of StreamReader.ReadLine:

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.

So if you're going to use StreamReader.ReadLine to read in the input, you could build up a new string with StringBuilder.Append (not AppendLine) as StreamReader.ReadLine implicitly removes the new line characters.

var filePath = "text.txt";
StringBuilder sb = new StringBuilder();

using (StreamReader reader = new StreamReader(filePath))
{
    while (!reader.EndOfStream)
    {
        sb.Append(reader.ReadLine());
    }
}

File.WriteAllText(filePath, sb.ToString());

i dont know if anyone else was having exactly this issue. here is the code i used to fix this issue.

      using (System.IO.FileStream File = new System.IO.FileStream(e.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
            {
                using (System.IO.StreamReader Reader = new System.IO.StreamReader(File, Encoding.Default))
                {
                    String CompleteData = Reader.ReadToEnd();
                    foreach (String Line in CompleteData.Split(new char[] { (char)13 }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (Line.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0].Contains("Raising event"))
                        {
                             //Do Stuff
                        }
                    }
                    Reader.Close();
                }
                File.Close();
            }

For some reason i had to do this because just using streamreader would throw an exception saying that the file is in use from another process.

It might help someone else at a later date..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!