【问题标题】:Casting stream to filestream [duplicate]将流转换为文件流[重复]
【发布时间】:2012-11-30 07:28:55
【问题描述】:

可能重复:
Convert a Stream to a FileStream in C#

我的问题是关于将流转换为 FileStream ...

基本上我需要这样做来获取文件的名称,因为如果我只有一个对象 Stream 它没有 Name 属性,而 FileStream 有...

那么如何正确地做到这一点,如何将 Stream 对象转换为 FileStream ...?

另一个问题是这个流来自 webResponse.GetResponseStream(),如果我将它转换为 FileStream,我就会把它弄空。基本上我也可以使用流,但我需要获取文件名。

我正在使用 3.5

有什么想法吗?

【问题讨论】:

标签: c# casting stream filestream


【解决方案1】:

使用as 运算符执行转换,如果Stream 实际上不是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
}

【讨论】:

    【解决方案2】:

    假设流实际上是一个文件流,以下应该可以解决问题:

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

    【讨论】:

      【解决方案3】:

      选项 1。如果您确定,Stream 对象是 FileStream

      var fileStream = (FileStream)stream;
      

      选项 2。如果您不确定Stream 对象是 FileStream,但如果是,它将很有用:

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

      请注意,转换为更具体的类型通常是一个信号,需要仔细查看您的代码,并可能对其进行重构。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-11
        • 1970-01-01
        • 2021-08-20
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多