2014-04-10 24 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();