如何读取文本文件中的最后10行?

时间:2011-12-22 09:11:50

标签: c# .net .net-micro-framework

我需要阅读我文件中的最后10行。文件大约是1MB,但我需要代码非常高效,因为它将在有限的设备中运行。

PD:我在this帖子中测试了代码,没有人为我工作。

修改 This代码无效,因为NETMF 4.1没有 GetByteCount GetString ,您知道其他任何方法吗?

2 个答案:

答案 0 :(得分:1)

这就是我最终如何解决的问题。无论如何代码太慢,所以如果你们有任何建议,请告诉我:

    public static string ReadEndTokens(string filename, Int64 numberOfTokens, Encoding encoding, string tokenSeparator)
    {
        lock (typeof(SDAccess))
        {
            PersistentStorage sdPS = new PersistentStorage("SD");
            sdPS.MountFileSystem();
            string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;

            int sizeOfChar = 1;//The only encoding suppourted by NETMF4.1 is UTF8
            byte[] buffer = encoding.GetBytes(tokenSeparator);


            using (FileStream fs = new FileStream(rootDirectory + @"\" + filename, FileMode.Open, FileAccess.ReadWrite))
            {
                Int64 tokenCount = 0;
                Int64 endPosition = fs.Length / sizeOfChar;

                for (Int64 position = sizeOfChar; position < endPosition; position += sizeOfChar)
                {
                    fs.Seek(-position, SeekOrigin.End);
                    fs.Read(buffer, 0, buffer.Length);

                    encoding.GetChars(buffer);
                    if (encoding.GetChars(buffer)[0].ToString() + encoding.GetChars(buffer)[1].ToString() == tokenSeparator)
                    {
                        tokenCount++;
                        if (tokenCount == numberOfTokens)
                        {
                            byte[] returnBuffer = new byte[fs.Length - fs.Position];
                            fs.Read(returnBuffer, 0, returnBuffer.Length);                          
                            sdPS.UnmountFileSystem();// Unmount file system
                            sdPS.Dispose();
                            return GetString(returnBuffer);
                        }
                    }
                }

                // handle case where number of tokens in file is less than numberOfTokens
                fs.Seek(0, SeekOrigin.Begin);
                buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                sdPS.UnmountFileSystem();// Unmount file system
                sdPS.Dispose();
                return GetString(buffer);
            }
        }
    }

    //As GetString is not implemented in NETMF4.1 I've done this method
    public static string GetString(byte[] bytes)
    {
        string cadena = "";
        for (int i = 0; i < bytes.Length; i++)
            cadena += Encoding.UTF8.GetChars(bytes)[i].ToString();
        return cadena;
    }

答案 1 :(得分:-1)

尝试:File.ReadLines(myFilePath);并使用Linq。 http://msdn.microsoft.com/en-us/library/dd383503.aspx