日期:2014-05-17 浏览次数:21121 次
private string getLast50() { string strSol=string.Empty; List<string> listFile=new List<string>(); StreamReader objSr =new StreamReader(@"c:\ss.txt",Encoding.Default); while(!objSr.EndOfStream){ listFile.Add(objSr.ReadLine()); } if(listFile.Count>50) { for (int i = listFile.Count - 50; i < listFile.Count-1; i++) { strSol+=listFile[i]+Environment.NewLine; } }else for(int i=0;i<listFile.Count;i++) { strSol+=listFile[i]+Environment.NewLine; } return strSol + listFile[listFile.Count-1]; }
------解决方案--------------------
对1楼的程序的修改:
private string getLast50()
{
string strSol=string.Empty;
List<string> listFile=new List<string>();
StreamReader objSr =new StreamReader(@"c:\ss.txt",Encoding.Default);
while(!objSr.EndOfStream){
listFile.Add(objSr.ReadLine());
if ( listFile.Count > 50 ) // 如果多于50行,就把最前面的一行删掉
listFile.RemoveAt(0);
}
for(int i=0;i<listFile.Count;i++)
{
strSol+=listFile[i]+Environment.NewLine;
}
return strSol + listFile[listFile.Count-1];
}
------解决方案--------------------
这种方式做聊天室你很快就会崩溃的。用个本地的sql express也行啊。
------解决方案--------------------
二进制方式读取,seek到最后往前缓冲区长度的地方,读到缓冲区,分析里面有多少换行符,不够的话,往前seek
------解决方案--------------------
思路被VMM说了。。。
参考如下代码:
FileStream vFileStream = new FileStream(@"c:\temp\temp.log", FileMode.Open, FileAccess.Read); byte[] vBuffer = new byte[0x1000]; int vReadLength; int vLineCount = 0; int vReadCount = 0; int j = 0; do { vFileStream.Seek(-vBuffer.Length * ++vReadCount, SeekOrigin.End); vReadLength = vFileStream.Read(vBuffer, 0, vBuffer.Length); for (int i = vReadLength - 1; i >= 0; i--) { j++; if (vBuffer[i] == 10) vLineCount++; if (vLineCount >= 9) { if (vReadCount > 1) { vBuffer = new byte[vFileStream.Length - j - 1]; vFileStream.Seek(j, SeekOrigin.End); vReadLength = vFileStream.Read(vBuffer, 0, vBuffer.Length); j = 0; } textBox1.Text = Encoding.Default.GetString(vBuffer, vReadLength - j, j); break; } } } while (vLineCount < 50 || vReadLength < vBuffer.Length); if (vLineCount < 50) textBox1.Text = Encoding.Default.GetString(vBuffer, 0, vReadLength); vFileStream.Close(); Text = vLineCount.ToString();
------解决方案--------------------
string[] lines = File.ReadAllLines("C:\\test.txt", System.Text.Encoding.Default);//编码看你情况而定 List<string> last50 = new List<string>();//也可以ArrayList last50=new ArrayList(); for (int i = lines.Length - 1; i >= lines.Length - 50 && i >= 0; i--) last50.Insert(0, lines[i]);
------解决方案--------------------