文本文件更新后,请始终阅读最后一行. [英] Always read last line when the text file have updated.
本文介绍了文本文件更新后,请始终阅读最后一行.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using (var fs = new FileStream("C:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var reader = new StreamReader(fs))
{
while (true)
{
var line = reader.ReadLine();
if (!String.IsNullOrEmpty(line))
{
MessageBox.Show("Line read: " + line);
朋友们,当前代码可以在运行应用程序时读取所有行,但是当文本文件仅被更新/修改时,我希望它读取最后一行吗?需要帮助吗?
Loginthiren
Hi friends, current code can read all line when running the application, but I want it to read the last line when ever the text file are updated/modify only? Need help on this please?
Loginthiren
推荐答案
你好,
这是一个使用VS2010/dotNet4/Vista的控制台项目示例;
Here is a Console Project example using VS2010/dotNet4/Vista;
static void Main( string[] args )
{
StreamReader sr = new StreamReader( File.OpenRead( "X:\\Temp\\MusicList.txt" ) );
if ( sr != null )
{
int x = 0, y = 0;
string s1 = "", s2 ="";
while( !sr.EndOfStream )
{
s1 = sr.ReadLine();
x = s1.Length;
Console.WriteLine( "{0} : {1} = {2}", y, s1, x );
y++;
}
Console.WriteLine( "\nNumber of Lines : {0} (Zero based index)", y );
Console.WriteLine( "Last Line Length : {0}", x );
Console.WriteLine( "\nEOF = FileLength @ {0}", sr.BaseStream.Position );
sr.BaseStream.Seek( ( sr.BaseStream.Length - 2 ), SeekOrigin.Begin );
// If 0x0D0A present, Subtract 2 more, Return/NewLine codes
if ( sr.Read() == 0x0D && sr.Read() == 0x0A )
{
x += 2;
}
sr.BaseStream.Seek( (sr.BaseStream.Length - x ), SeekOrigin.Begin );
Console.WriteLine( "Last Line FPOS @ {0}", sr.BaseStream.Position );
s2 = sr.ReadLine();
if ( s1 == s2 )
{
Console.WriteLine( "Match" );
}
else
{
Console.WriteLine( "FPOS MisMatch" );
}
sr.Close();
}
}
以下是输出结果:
请记住,CR/LF代码在读入对象类型字符串后会被删除.除非另有说明
Just remember, CR/LF codes, are dropped after the read into object type string. Unless stated
否则在流中.
希望这会有所帮助! :)
Hope this helps! :)
这篇关于文本文件更新后,请始终阅读最后一行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文