/
maxja
/
OneSTools.TechLog-Vault
Обзор
Документация
Войти
/
maxja
/
OneSTools.TechLog-Vault
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
OneSTools.TechLog/StreamReaderExtensions.cs
43 строки
2 KB
Акпаев Евгений Александрович
Фиксация промежуточной работы
28 янв 2021, 00:44
28 янв 2021, 00:44
6a49a7d
Код
Авторство
О чём код?
using System; using System.IO; using System.Reflection; namespace OneSTools.TechLog { internal static class StreamReaderExtensions { static readonly FieldInfo charPosField = typeof(StreamReader).GetField("_charPos", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); static readonly FieldInfo byteLenField = typeof(StreamReader).GetField("_byteLen", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); static readonly FieldInfo charBufferField = typeof(StreamReader).GetField("_charBuffer", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); public static long GetPosition(this StreamReader reader) { // shift position back from BaseStream.Position by the number of bytes read // into internal buffer. var byteLen = (int)byteLenField.GetValue(reader); var position = reader.BaseStream.Position - byteLen; // if we have consumed chars from the buffer we need to calculate how many // bytes they represent in the current encoding and add that to the position. var charPos = (int)charPosField.GetValue(reader); if (charPos > 0) { var charBuffer = (char[])charBufferField.GetValue(reader); var encoding = reader.CurrentEncoding; var bytesConsumed = encoding.GetBytes(charBuffer, 0, charPos).Length; position += bytesConsumed; } return position; } public static void SetPosition(this StreamReader reader, long position) { reader.DiscardBufferedData(); reader.BaseStream.Seek(position, SeekOrigin.Begin); if (reader.BaseStream.Position != position) throw new Exception("Couldn't set the stream position"); } } }