开发者

Removing \r from lines read from file

I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOut开发者_如何学编程put.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

cleanLine.Replace("\r",""); //assigns a value to nothing

I should have assigned cleanLine to cleanLine.Replace();

cleanLine = cleanLine.Replace("\r","");


If you call:

string[] lines = File.ReadAllLines(location);

it will remove both the '\r' and '\n' from each line for you.


I'm pretty sure running fileOutput.Replace("\r","") would be better than calling a replace for each of the strings attained after the split. It might fix your problem as well.


I think you're misunderstanding how strings work in C#, and how text files generally work on Windows.

On Windows a new line is delimited by Carriage Return (\r), and Line Feed (\n)? So, this is "normal".

Secondly, in C# strings are immutable.

if (cleanLine.Contains("\r")) cleanLine.Replace("\r", ""); does not assign the 'cleaned' value.

You would need to use cleanLine = cleanLine.Replace("\r","");

Thirdly, from a style perspective in C# - you should place code blocks on another line, and surround them with brackets. It's valid syntax not to, but it reduces readability.

As a last thing - you could simply open the text file and call ReadLine rather than needing to do string replacement as you're doing now.


In Windows, the line indicator is actually \r\n, so your best bet may be to do an initial replace of "\r\n" with some other character that isn't found elsewhere in the file (like maybe "|"), and then split on the replaced character. Otherwise, if you just replace "\r", you may end up replacing a "\r" that isn't actually at the end of a line (although this is pretty doubtful).

How are you reading the file in the first place? The .Net TextReader class has a ReadLine() method, the use of which would let you avoid this particular problem entirely.


As others have suggested, use File.ReadAllLines() instead. It will split on \n as well as \r\n. Your sample can be rewritten as:

SettingsManager.proxies.Clear();
foreach (string line in File.ReadAllLines(location))
    SettingsManager.proxies.Add(line);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜