Giter VIP home page Giter VIP logo

argus.io.reversefilereader's Introduction

Reverse File/Stream Reader

NuGet version (ReverseFileReader) NuGet version (ReverseFileReader)

A file/stream reader that is designed to iterate over a file or a stream line by line in reverse order in a way that does not read all of the lines into memory at one time. This supports .NET Standard, the full framework as well as the Windows Universal Platform (UWP) apps.

Although this is geared towards files it will read any Stream line by line in reverse order.

.Net Framework Support

  • .NET 6.0
  • .NET 5.0
  • .NET Standard 2.1
  • .NET Standard 2.0
  • .NET Framework 4.7.2
  • .NET Framework 4.7.1
  • .NET Framework 4.7
  • .NET Framework 4.6.2
  • .NET Framework 4.6.1
  • .NET Framework 4.6
  • .NET Framework 4.5.2
  • .NET Framework 4.5.1
  • .NET Framework 4.5
  • .NET Framework 4

Read a file with CrLf line endings

C#
var sb = new StringBuilder();

using (var reader = new Argus.IO.ReverseFileReader(@"C:\Temp\log-file.txt"))
{
    while (!reader.StartOfFile)
    {
        sb.AppendLine(reader.ReadLine());
    }
}

Read a file with Lf line endings (Cr also supported with a change to the LineEnding property)

C#
var sb = new StringBuilder();

using (var reader = new Argus.IO.ReverseFileReader(@"C:\Temp\log-file.txt"))
{
    reader.LineEnding = Argus.IO.LineEnding.Lf;

    while (!reader.StartOfFile)
    {
        sb.AppendLine(reader.ReadLine());
    }
}

Windows Universal Platform Example (UWP)

The FileStream is available in UWP but for all intensive purposes is unusable due to the apps being sandboxed. If you instantiate the ReverseFileReader with a file path it will likely end with a permissions exception. Instead, you'll get a StorageFile and then pass its Stream off to the ReverseFileReader which will work.

One thing to note that could cause a related issue is that since Windows 10 build 14393 the TextBox and RichEditBox use only a carriage return (when those save they only save with a carriage return unless you intervene). Pay attention to that if it becomes an issue. In the near future I will provide an auto-detect method that will attempt to infer what line endings the file is using.

C#
/// <summary>
/// Opens a document and puts the contents into a TextBox named TextBoxMain.
/// </summary>
/// <returns></returns>
private async Task OpenDocument()
{
    var picker = new Windows.Storage.Pickers.FileOpenPicker
    {
        SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
    };

    picker.FileTypeFilter.Add(".txt");
    var OpenStorageFile = await picker.PickSingleFileAsync();

    if (OpenStorageFile != null)
    {
        var sb = new StringBuilder();

        using (var stream = await OpenStorageFile.OpenStreamForReadAsync())
        {
            using (var reader = new Argus.IO.ReverseFileReader(stream))
            {
                reader.LineEnding = Argus.IO.LineEnding.CrLf;

                while (!reader.StartOfFile)
                {
                    sb.AppendLine(reader.ReadLine());
                }

            }
        }

        TextBoxMain.Text = sb.ToString();
        return;
    }
}

Tail

I have provided a console program that is a lightweight tail utility. It reads lines of the end of the provided file. If more lines are requested than the file has the entire file is returned.

Syntax: tail <filename>
        tail <filename> <number of lines to fetch>

argus.io.reversefilereader's People

Contributors

blakepell avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

argus.io.reversefilereader's Issues

Read Twice

I am looking for some methods help me to read log files from tail to head.
your project is great!
but int this code https://github.com/blakepell/Argus.IO.ReverseFileReader/blob/master/src/Argus.IO.ReverseFileReader/IO/ReverseFileReader.cs

byte[] buf = new byte[1];
            long position = _stream.Position;

            while (_stream.Position > 0)
            {
                buf.Initialize();

                _stream.Seek(-1, SeekOrigin.Current);

                // Read one char
                _stream.Read(buf, 0, 1);

                // Move it back
                _stream.Seek(-1, SeekOrigin.Current);

                if (buf[0] == 10)
                {
                    // Move it back again.
                    _stream.Seek(-1, SeekOrigin.Current);

                    _stream.Read(buf, 0, 1);

                    if (buf[0] == 13)
                    {
                        break;
                    }
                }
            }

            int count = (int)(position - _stream.Position);
            byte[] line = new byte[count];

            _stream.Read(line, 0, count);
            _stream.Seek(-count, SeekOrigin.Current);

            return this.Encoding.GetString(line).Trim(new[] { '\r', '\n' });

Read same char twice, you can improve it.
By the way, _stream.Read(buf, 0, 1); is slow.
_stream.Read(buf, 0, bufferSize); char ch = buf[wantedPosition - bufferStartPosition]; may be better

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.