Cri*_*rbe 6 c# encoding newline streamreader text-files
我必须处理一个文本文件并检查它是否以回车符结束.
我必须阅读整个内容,进行一些更改并将其重新写入目标文件,保持与原始格式完全相同的格式.这就是问题所在:我不知道原始文件是否包含换行符.
我已经尝试过了:
如何有效地读取文件的所有文本并确定它是否以换行符结束?
通过读取文件后ReadLine(),您可以在文件末尾之前搜索两个字符,并将这些字符与CR-LF进行比较:
string s;
using (StreamReader sr = new StreamReader(@"C:\Users\User1\Desktop\a.txt", encoding: System.Text.Encoding.UTF8))
{
while (!sr.EndOfStream)
{
s = sr.ReadLine();
//process the line we read...
}
//if (sr.BaseStream.Length >= 2) { //ensure file is not so small
//back 2 bytes from end of file
sr.BaseStream.Seek(-2, SeekOrigin.End);
int s1 = sr.Read(); //read the char before last
int s2 = sr.Read(); //read the last char
if (s2 == 10) //file is end with CR-LF or LF ... (CR=13, LF=10)
{
if (s1 == 13) { } //file is end with CR-LF (Windows EOL format)
else { } //file is end with just LF, (UNIX/OSX format)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3789 次 |
| 最近记录: |