18

Is there any way to know the type of the FileStream. I have a function that takes a FileStream object and I want to determine the file extension based on that FileStream.

Chris Haas
  • 47,821
  • 10
  • 127
  • 248
Abdul Samad
  • 4,840
  • 12
  • 52
  • 66

3 Answers3

24
 string extension = Path.GetExtension(myFileStream.Name);
Tomislav Markovski
  • 11,818
  • 4
  • 43
  • 69
23

If the stream is really a FileStream then you should be able to do the following

var ext = Path.GetExtension(fileStream.Name);

If it's a plain old Stream though then it's not generally possible to get the extension because a Stream can be created for any stream of bytes. It doesn't have to have a backing file.

Update

As Chris pointed out in the comments there is another SO question which is relevant to this discussion. It's discussing heuristics for determining type of a byte[] which can then be mapped to a probable original signature.

It's by no means foolproof but may be helpful to you.

Community
  • 1
  • 1
JaredPar
  • 673,544
  • 139
  • 1,186
  • 1,421
4

Yes, using the file name the following will return .txt (including the .):

var path = myFileStream.Name;
return Path.GetExtension(path);
Devin Burke
  • 13,074
  • 11
  • 51
  • 80