Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting stream to filestream [duplicate]

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?

like image 525
Alnedru Avatar asked Nov 30 '12 07:11

Alnedru


People also ask

How do I write from one stream to another?

CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

When to use FileStream c#?

The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.

What should you do with a file stream when you are finished with it?

FileStream buffers input and output for better performance. This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try / catch block.


2 Answers

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
}
like image 77
mlorbetske Avatar answered Sep 21 '22 18:09

mlorbetske


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

var name = ((FileStream)stream).Name;
like image 21
Teppic Avatar answered Sep 21 '22 18:09

Teppic