I recently read on Setting position index of filestream that it is possible to use
seek()
method of BaseStream
class.
But now, using .Net Framework 4.8
or greater these 2 functions seem to have been deleted.
Which stream in .Net 4.8
or greater does implement this 2 functions ?
I search a solution that is distinct from My.MyComputer.SystemFile.Seek() and is not restricted to using old VB 6 FileOpen()
method !
The System.IO.FileStream
class inherits the System.IO.Stream
class. The latter provides the base functionality for all streams while the former provides functionality for streams backed by files. The Seek
method is a member of the Stream
class and thus every stream, regardless of type, has that method. That's true up to .NET 6 and will continue to be true as long as .NET exists.
The Seek
method might throw a NotSupportedException
in some cases, in which case the CanSeek
property of that stream will be False
. If you have a stream and you're not sure whether it can seek or not, test that property before calling Seek
to ensure no exception will be thrown. In the case of a FileStream
, the documentation (which you should already have read) tells us when to expect that property to be False
:
true if the stream supports seeking; false if the stream is closed or if the FileStream was constructed from an operating-system handle such as a pipe or output to the console.
You can read the documentation of other types of streams to see whether they support seeking, e.g. MemoryStream
does and NetworkStream
doesn't. Basically, seeking requires random access to all the data rather than just sequential access.
There is no BaseStream
property on a FileStream
. The property you refer to is a member of StreamReader
class. That property will return a Stream
reference to the stream being read. That could be a FileStream
, NetworkStream
, MemoryStream
or whatever. If you have a StreamReader
and you want to seek to a specific position in the underlying stream but you don't know whether it is supported or not then you get the BaseStream
, test the CanSeek
property and, if it's True
, call the Seek
method.
With myStreamReader.BaseStream
If .CanSeek Then
'Advance the file pointer 64 bytes.
.Seek(64L, SeekOrigin.Current)
End If
End With
That will work no matter what type of stream backs the reader because CanSeek
and Seek
are members of Stream
and StreamReader.BaseStream
is type Stream
.