C# 将流转换为文件流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13640768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting stream to filestream
提问by Alnedru
Possible Duplicate:
Convert a Stream to a FileStream in C#
可能的重复:
在 C# 中将流转换为 FileStream
My question is regarding the cast of stream to FileStream ...
我的问题是关于流到 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 ...
基本上我需要这样做来获取文件的名称,因为如果我只有一个对象 Stream 它没有 Name 属性,当 FileStream 确实......
So how to do it properly, how to cast Stream object to FileStream ...?
那么如何正确地做到这一点,如何将 Stream 对象转换为 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.
另一个问题是这个流来自 webResponse.GetResponseStream() ,如果我将它转换为 FileStream ,我会得到它为空。基本上我也可以使用流,但我需要获取文件名。
I'm using 3.5
我正在使用 3.5
Any ideas?
有任何想法吗?
采纳答案by mlorbetske
Use the asoperator to perform the cast, if the Streamis not actually a FileStream, nullwill be returned instead of throwing an exception.
使用as运算符执行强制转换,如果Stream实际上不是 a FileStream,null则将返回而不是抛出异常。
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
}
回答by Teppic
Assuming the stream actually is a file stream, the following should do the trick:
假设流实际上是一个文件流,以下应该可以解决问题:
var name = ((FileStream)stream).Name;
回答by Dennis
Option 1. If you're sure, that Streamobject is a FileStream:
选项 1. 如果您确定,该Stream对象是一个FileStream:
var fileStream = (FileStream)stream;
Option 2. If you're notsure, that Streamobject is a FileStream, but if it is, it will be useful:
选项2.如果你不肯定的,那Stream对象是FileStream的,但如果是这样,这将是有用的:
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.
请注意,转换为更具体的类型通常是仔细查看代码并可能对其进行重构的信号。

