问题描述
我正在尝试从日志文件中的每一行文本中删除所有换行"字符.
I'm trying to remove any "new line" characters from each line of text in my log file.
以下是我正在使用Stream Reader读取的示例条目:-
Below is an example entry that I am reading in with a Stream Reader :-
<![LOG[Raising event:
[SMS_CodePage(850), SMS_LocaleID(2057)]
instance of SoftDistProgramStartedEvent
{
AdvertisementId = "000216F6";
ClientID = "GUID:B55C2757-CBAE-468E-B54F-46CAF2ECF68F";
CommandLine = "\"C:\\WINNT\\system32\\cscript.exe\" /nologo Shutdown_Desktops_Overnight.vbs";
DateTime = "20130211080211.784000+000";
MachineName = "DWD*****";
PackageName = "0000073C";
ProcessID = 2516;
ProgramName = "Shutdown Desktops Overnight";
SiteCode = "S00";
ThreadID = 3640;
UserContext = "NT AUTHORITY\\SYSTEM";
WorkingDirectory = "C:\\WINNT\\system32\\CCM\\Cache\\0000073C.1.System\\";
};
]LOG]!><time="08:02:11.800+000" date="02-11-2013" component="execmgr" context="" type="1" thread="3640" file="event.cpp:522">
在实际的日志文件中,该文件在文件中显示为一行,而新行字符"(New Line Characters)替换为一个正方形.
In the actual Logfile this is displayed as one line in the file, with the "New Line Characters" replaced with a square.
我正在使用以下代码读取日志条目:-
I'm using the following code to read in the log entries :-
using (StreamReader sr = new StreamReader(@"C:\Documents and Settings\riversd\Desktop\Logfile2.log"))
{
string Line;
while ((Line = sr.ReadLine()) != null)
{
}
}
问题在于,当StreamReader从txt文件读取此条目时,它会在以下位置中断:-
The issue is that when the StreamReader reads this entry from the txt file it breaks at :-
"<![LOG[Raising event:"
我需要即时删除此条目中的所有换行符.我不想将整个文件读到内存中然后再删除它们,我宁愿在读取每个日志时对其进行处理.
I need to remove all new line characters in this entry, on the fly. I don't want to read the entire file into memory and then remove them, I'd rather deal with each log as I read it.
有可能吗?
推荐答案
sr.ReadLine().Replace(Environment.NewLine, String.Empty);
如果行尾不是 \ r \ n
而是 \ n
,则可以使用正则表达式:
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);
这篇关于Stream Reader Readline检测换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!