Casting stream to filestream

48,934

Solution 1

Use the as operator to perform the cast, if the Stream is not actually a FileStream, null will be returned instead of throwing an exception.

Stream stream = ...;
FileStream fileStream = stream as FileStream;

if(fileStream != null)
{
    //It was really a file stream, get your information here
}
else
{
    //The stream was not a file stream, do whatever is required in that case
}

Solution 2

Assuming the stream actually is a file stream, the following should do the trick:

var name = ((FileStream)stream).Name;

Solution 3

Option 1. If you're sure, that Stream object is a FileStream:

var fileStream = (FileStream)stream;

Option 2. If you're not sure, that Stream object is a FileStream, but if it is, it will be useful:

var fileStream = stream as FileStream;
if (fileStream != null)
{
    // specific stuff here
}

Note, that casting to more specific type usually is a signal to look carefully at your code and, possibly, to refactor it.

Share:
48,934
Alnedru
Author by

Alnedru

Updated on July 09, 2022

Comments

  • Alnedru
    Alnedru almost 2 years

    Possible Duplicate:
    Convert a Stream to a FileStream in C#

    My question is regarding the cast of stream to FileStream ...

    Basically I need to do that to get the name of the file, because if I have just an object Stream it doesn't have the Name property, when FileStream does ...

    So how to do it properly, how to cast Stream object to FileStream ...?

    Another problem is that this stream comes from webResponse.GetResponseStream() and if I cast it to FileStream I get it empty. Basically I could also use stream but i need to get the file name.

    I'm using 3.5

    Any ideas?