2014-04-10 47 views
0

我是相当新的,但我觉得我非常接近做这项工作,我只需要一点帮助!我想创建一个DLL,它可以读取并返回在另一个应用程序中打开的文件中的最后一行。这就是我的代码的样子,我只是不知道在while语句中放什么。在打开的文件中阅读最后一行

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 

namespace SharedAccess 
{ 
    public class ReadShare { 
     static void Main(string path) { 

      FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
      StreamReader reader = new StreamReader(stream); 

      while (!reader.EndOfStream) 
      { 
       //What goes here? 
      } 
     } 
    } 
} 

回答

3

要阅读的最后一行,

var lastLine = File.ReadLines("YourFileName").Last(); 

如果它是一个大的文件

public static String ReadLastLine(string path) 
{ 
    return ReadLastLine(path, Encoding.ASCII, "\n"); 
} 
public static String ReadLastLine(string path, Encoding encoding, string newline) 
{ 
    int charsize = encoding.GetByteCount("\n"); 
    byte[] buffer = encoding.GetBytes(newline); 
    using (FileStream stream = new FileStream(path, FileMode.Open)) 
    { 
     long endpos = stream.Length/charsize; 
     for (long pos = charsize; pos < endpos; pos += charsize) 
     { 
      stream.Seek(-pos, SeekOrigin.End); 
      stream.Read(buffer, 0, buffer.Length); 
      if (encoding.GetString(buffer) == newline) 
      { 
       buffer = new byte[stream.Length - stream.Position]; 
       stream.Read(buffer, 0, buffer.Length); 
       return encoding.GetString(buffer); 
      } 
     } 
    } 
    return null; 
} 

我refered这里, How to read only last line of big text file

+4

但是,如果文件很大,这将会非常低效。有更复杂但更有效的方法。 –

+0

+0:可以工作,但我不知道它是否以正确的'FileShare'标记打开文件 - “在另一个应用程序*中打开的文件中的最后一行*”。 –

+0

@JonSkeet是的,我认为.Seek()会更有效率 – Sajeetharan

0

文件readlines方法应该为你工作。

var value = File.ReadLines("yourFile.txt").Last(); 
相关问题