public static void Main() { string path = @"d:\MyTest.txt"; if (File.Exists(path)) { File.Delete(path); } using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("This"); sw.WriteLine("is some text"); sw.WriteLine("to test"); sw.WriteLine("Reading"); } using (StreamReader sr = new StreamReader(path)) { char[] cArray = new char[128]; int index = 0; while (sr.EndOfStream == false) { sr.Read(cArray, index, 1);
if (cArray[index] == '\n') { Console.WriteLine("\t--n换行"); } else if (cArray[index] == '\r') { Console.WriteLine("\t--r回车"); } else { Console.Write(cArray[index]); }
{
String str = reader.ReadToEnd();
String[] result = str.Split(new String[] { "\r\n" }, StringSplitOptions.None);
foreach (string s in result)
{
Console.WriteLine(s);
}
}
{
ExistsFile(Server.MapPath("test/weather.txt"));//检查文件是否存在
//读取文件
StreamReader sr = new StreamReader(Server.MapPath("test/weather.txt"), System.Text.Encoding.Default);
try
{
string input = sr.ReadToEnd();
sr.Close(); //有的平台只有\n表示换行 如 mac,linux之流,windows平台换行使用\r\n
//所以就连.net框架都有一个 System.Environment.NewLine; 以实现不同平台的换行.</DIV>
input = input.Replace("\r\n", "").Replace("\n", ""); //注:\r\n在winform中是换行,在html的文档内换行,显示出来的页面是不会换行的.
this.TextBox1.Text = input;
}
catch
{
Response.Write("<script>alert('文件读取失败');</script>");
}
}
2、如果一定要区分,可以继承StreamReader并重写ReadLine函数(不是太容易)。
3、另一个效率比较低的方法为:
string[] lines = File.ReadAllText("my.txt").Split(new string[] { "\r\n" }, StringSplitOptions.None);
using System.IO;class Test
{
public static void Main()
{
string path = @"d:\MyTest.txt";
if (File.Exists(path))
{
File.Delete(path);
} using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
} using (StreamReader sr = new StreamReader(path))
{
char[] cArray = new char[128];
int index = 0; while (sr.EndOfStream == false)
{
sr.Read(cArray, index, 1);
if (cArray[index] == '\n')
{
Console.WriteLine("\t--n换行");
}
else if (cArray[index] == '\r')
{
Console.WriteLine("\t--r回车");
}
else
{
Console.Write(cArray[index]);
}
index++;
}
}
Console.ReadKey();
}
}
上面的回复也有很好的解决办法,多谢各位的指教!