【问题标题】:Read last line in open file [duplicate]读取打开文件中的最后一行 [重复]
【发布时间】:2014-04-10 17:26:18
【问题描述】:

我对这一切还很陌生,但我觉得我已经接近完成这项工作了,我只需要一点帮助!我想创建一个 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?
            }
        }
    }
}

【问题讨论】:

    标签: c# fileshare


    【解决方案1】:

    读取最后一行,

    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;
    }
    

    我在这里提到, How to read only last line of big text file

    【讨论】:

    • 但是,如果文件很大,那将是非常低效的。还有更复杂但很多更有效的方法。
    • +0: 可能有效,但我不知道它是否使用正确的FileShare 标志打开文件 - 文件中的最后一行在另一个应用程序中打开”。
    • @JonSkeet 是的,我认为 .Seek() 会更有效率
    • 效果很好!
    【解决方案2】:

    文件读取行应该适合你。

    var value = File.ReadLines("yourFile.txt").Last();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 2010-09-06
      • 1970-01-01
      相关资源
      最近更新 更多