user584018
user584018

Reputation: 11304

C#: how to generate StreamContent for partial bytes

How to generate StreamContent of a filestream say example from bytes 5 to 10, I would like to exclude the bytes from 0 to 5.

string file = @"C:\Files\test.txt";


        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        {

            var X = fs.Length;

            //how to read  StreamContent from bytes from 5 to 10

            var Y = new StreamContent(fs);
        }

Upvotes: 0

Views: 880

Answers (3)

Anthony McGrath
Anthony McGrath

Reputation: 802

You can also read the bytes from a FileStream using the MemoryStream class. I believe this may be a way to read bytes 5 to 10.

  using (var ms = new MemoryStream())
  {
      if (fs.CanSeek) 
      {
          fs.Seek(5, SeekOrigin.Begin);
          fs.CopyTo(ms, 5);

          //byte[] b = ms.ToArray();
          // create a StreamContent object
          var sc = new StreamContent(ms);
      }
  }

Upvotes: 1

cdhowie
cdhowie

Reputation: 168998

I'm going to assume the following:

  • "from bytes 5 to 10" -- You want to read from 5 inclusive to 10 exclusive, zero-based. That is, you want to read 5 bytes starting at the sixth byte in the file (the byte with index 5, if the first byte in the file has index 0).
  • "exclude the bytes from 0 to 5" -- Same deal here. I'm assuming 0 inclusive to 5 exclusive, zero-based.

To visualize what I believe you are asking:

Bytes:    #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
Indices:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14
You want to read these:  ^^^^^^^^^^^^^

If the stream is seekable (as file streams are), seek to position 5 and then read 5 bytes:

fs.Position = 5;

var buffer = new byte[5];
var bytesRead = fs.Read(buffer, 0, 5);

if (bytesRead == 5) {
    // Success, process the buffer
} else {
    // Partial read or end-of-file.
}

If the stream is not seekable (think a network socket or other pipe, for example), you need to consume and discard the bytes you want to skip. The simplest way to achieve this would be to read 10 bytes and simply ignore the first five. (If you wanted to skip a few hundred megabytes then we would want an alternative strategy, as it's probably not a great idea to hold a few hundred megabytes of unneeded data in memory.)

var buffer = new byte[10];
var bytesRead = fs.Read(buffer, 0, 10);

if (bytesRead == 10) {
    // Success, process the buffer starting at index 5.
} else {
    // Partial read or end-of-file.
}

You can use the CanSeek stream property to determine whether any arbitrary Stream object is seekable.

Upvotes: 2

NagarajKaundinya
NagarajKaundinya

Reputation: 51

Use following line instead. Writes from 5th character.

Console.WriteLine(sr.ReadToEnd().ToString().Substring(5,5));

Cheers, Nagaraj

Upvotes: 0

Related Questions