Skip to content

Instantly share code, notes, and snippets.

@ScottKaye
Created September 22, 2018 01:35
Show Gist options
  • Save ScottKaye/32edf21ed04ab872d07082d6daddcbe5 to your computer and use it in GitHub Desktop.
Save ScottKaye/32edf21ed04ab872d07082d6daddcbe5 to your computer and use it in GitHub Desktop.
Reads X lines from a file, stopping each line after Y characters.
void Main()
{
var path = @"R:\test.txt";
const int MAX_LINE_LENGTH = 15;
const int MAX_LINE_COUNT = 15;
using (var stream = GetTruncatedFile(path, MAX_LINE_LENGTH, MAX_LINE_COUNT))
using (var reader = new StreamReader(stream))
{
reader.ReadToEnd().Dump();
}
}
public MemoryStream GetTruncatedFile(string path, int maxLineLength, int maxLineCount)
{
if (maxLineLength == 0) throw new ArgumentException("Line length must be greater than 0.", nameof(maxLineLength));
var outputStream = new MemoryStream((maxLineCount * maxLineLength) + maxLineCount - 1);
using (var mmf = MemoryMappedFile.CreateFromFile(path))
using (var mmfStream = mmf.CreateViewStream())
{
var lineBuffer = new byte[maxLineLength];
while (maxLineCount-- > 0)
{
var position = 0;
while (position < maxLineLength)
{
var c = mmfStream.ReadByte();
if (c == '\n' || c <= 0)
{
break;
}
lineBuffer[position] = (byte)c;
++position;
}
outputStream.Write(lineBuffer, 0, position);
outputStream.WriteByte((byte)'\n');
--mmfStream.Position;
int last;
while ((last = mmfStream.ReadByte()) != '\n' && last > 0) ;
if (last <= 0) break;
}
}
// Trim off final \n
outputStream.SetLength(outputStream.Length - 1);
outputStream.Flush();
outputStream.Position = 0;
return outputStream;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment