Reputation: 11304
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
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
Reputation: 168998
I'm going to assume the following:
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
Reputation: 51
Use following line instead. Writes from 5th character.
Console.WriteLine(sr.ReadToEnd().ToString().Substring(5,5));
Cheers, Nagaraj
Upvotes: 0