2011-12-22 108 views
1

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

PD:我在this后测试的代码,并没有一个是为我工作。

编辑 This代码是不工作的,因为NETMF 4.1没有GetByteCount的GetString,你知不知道任何其他方式做到这一点?

+0

你能解释更准确地说什么是不为你工作?你是否收到错误信息?实际结果与预期结果有什么不同? – 2011-12-22 09:15:24

+2

您是否尝试过在http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp/452945#452945的代码?请注意,您需要说明文件的编码 - 这会产生巨大的差异。 – 2011-12-22 09:16:04

+0

没有工作,你需要扩大该部分 – V4Vendetta 2011-12-22 09:16:18

回答

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; 
    } 
相关问题