내 파일에서 마지막 10 줄을 읽어야합니다. 파일은 약 1MB이지만 제한된 장치에서 실행되므로 코드가 매우 효율적이어야합니다.텍스트 파일에서 마지막 10 줄을 읽으려면 어떻게해야합니까?
PD : this 게시물에 코드를 테스트했지만 아무도 저에게 효과가 없습니다.
편집 This 코드는이 작업을 수행하려면 다른 방법을 알고,하여 GetStringGetByteCount 및 이 없기 때문에 NETMF 4.1의 작동하지 않는 이유는 무엇입니까?
내 파일에서 마지막 10 줄을 읽어야합니다. 파일은 약 1MB이지만 제한된 장치에서 실행되므로 코드가 매우 효율적이어야합니다.텍스트 파일에서 마지막 10 줄을 읽으려면 어떻게해야합니까?
PD : this 게시물에 코드를 테스트했지만 아무도 저에게 효과가 없습니다.
편집 This 코드는이 작업을 수행하려면 다른 방법을 알고,하여 GetStringGetByteCount 및 이 없기 때문에 NETMF 4.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;
}
보십시오 : 당신의 어떤 조언이 있다면, 제발 말해 어쨌든 코드가 너무 느 File.ReadLines (myFilePath를); Linq를 사용하십시오. http://msdn.microsoft.com/en-us/library/dd383503.aspx
더 정확하게 설명하지 않겠습니까? 오류 메시지가 나타 납니까? 실제 결과가 예상 결과와 다른 점은 무엇입니까? –
http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reverse-with-iterator-in-c-sharp/452945#452945에서 코드를 사용해 보셨습니까? 파일의 인코딩이 무엇인지 말할 필요가 있습니다. 이는 큰 차이를 만듭니다. –
아무 작업도하지 않아도됩니다 해당 부분을 확장해야합니다 – V4Vendetta