2012-02-11 1273 views
0

任何想法如何读取包含大约30行的文件的最后一行或最后两行,\n重点关注性能速度?用C#读取文件最后一行的高性能方法

编辑:

string[] splitedArray= input.Split('\n'); 
string lastLine = splitedArray[splitedArray.Length-1]; 

使用C#

+0

几乎重复:?如何阅读 - 一个文本文件,逆向与迭代器功能于C-锐] (http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp?) – nawfal 2014-05-26 09:36:42

回答

3

如果您创建一个新的IO.FileStream()对象,有一个.Seek()方法,可以让你指定: 快于东西该文件的结尾作为您想要查找的位置的一部分。然而,在这一点上,没有直截了当的方法来查看最后一行开始的位置。你必须向后走才能找到一条线,或者如果你知道最后一条线是什么样子的(因此它有多长时间),你可以猜测你需要的距离有多远寻求和进一步。 使用FileStream.CanSeek属性来确定当前实例是否支持查找。有关其他信息,请参阅Stream.CanSeek。

FileStream fileStream = new FileStream(fileName, FileMode.Open) 
// Set the stream position to the end of the file. 
fileStream.Seek(0, SeekOrigin.End); 

然后去了中环,直到你得到你/ N

,你也可以在此的其他问题阅读:How to read a text file reversely with iterator in C#

+0

是否有任何方式如何从结尾读取字符串? – 2012-02-11 11:50:27

+0

我编辑了我的答案,注意在我的答案中性能已经优化,不需要读取整个文件! – 2012-02-11 12:00:40

11

从我的头顶

string lastline = input.Substring(
    input.LastIndexOf('\n')); 
+1

'string lastline = input.Substring(input.LastIndexOf('\ n'))'这里就够了。 – 2012-02-11 11:52:10

+0

@Lester我更新了我的头和我的答案;-) – rene 2012-02-11 11:53:46

+1

在你的答案中,性能是最坏的,你需要读取所有字符串到字符串,这是没有必要的。 – 2012-02-11 11:59:41

1

如果读取任何文件时需要更好的性能,您可以去读取/写入内存映射文件,即在低级别的API上工作。

0

(注意:它不是C#但VB.NET)前几年我翻译了a function that I created for Python。不知道搜索\n仅是最好的选择...

Public Function tail(ByVal filepath As String) As String 
    ' @author marco sulla ([email protected]) 
    ' @date may 31, 2016 

    Dim fp As String = filepath 
    Dim res As String 

    Using f As FileStream = File.Open(fp, FileMode.Open, FileAccess.Read) 
     Dim f_info As New FileInfo(fp) 
     Dim size As Long = f_info.Length 
     Dim start_pos As Long = size - 1 

     If start_pos < 0 Then 
      start_pos = 0 
     End If 

     If start_pos <> 0 Then 
      f.Seek(start_pos, SeekOrigin.Begin) 
      Dim mychar As Integer = f.ReadByte() 

      If mychar = 10 Then ' newline 
       start_pos -= 1 
       f.Seek(start_pos, SeekOrigin.Begin) 
      End If 

      If start_pos = 0 Then 
       f.Seek(start_pos, SeekOrigin.Begin) 
      Else 
       mychar = -1 

       For pos As Long = start_pos To 0 Step -1 
        f.Seek(pos, SeekOrigin.Begin) 

        mychar = f.ReadByte() 

        If mychar = 10 Then 
         Exit For 
        End If 
       Next 
      End If 
     End If 

     Using r As StreamReader = New StreamReader(f, Encoding.UTF8) 
      res = r.ReadLine() 
     End Using 
    End Using 

    Return res 
End Function 
相关问题