使用Stream显示Image * .ico

时间:2012-03-01 04:01:40

标签: c# asp.net stream

我想展示带有*.ico扩展名的图片,并使用Stream来执行此操作。但我有一个问题。

使用扩展程序*.jpg*.bmp ...图片显示确定但*.ico,但未显示

这是我的代码:

 private void OutputStream(string fileName)
    {
        try
        {
            Stream dataStream = null;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPFile spFile = web.GetFile(fileName);
                    dataStream = spFile.OpenBinaryStream();
                    this.HandleOutputStream(dataStream);
                });

        }
        catch (System.Threading.ThreadAbortException exTemp)
        {
            logger.Error("KBStreamPicture::OutputStream", exTemp);
        }
        catch (Exception ex)
        {
            //System.Diagnostics.Debug.Write("OutputStream::" + ex);
            logger.Error("KBStreamPicture::OutputStream", ex);
        }
    }

private void HandleOutputStream(Stream dataStream)
    {
        const int bufferSize = 16384; //16KB 

        using (Stream file = dataStream)
        {
            if (file != null)
            {
                this.Page.Response.Clear();
                this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
                this.Page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20)); //only cache 20 minutes
                byte[] buffer = new byte[bufferSize];
                int count = file.Read(buffer, 0, bufferSize);

                while (count > 0)
                {
                    if (this.Page.Response.IsClientConnected)
                    {
                        this.Page.Response.OutputStream.Write(buffer, 0, count);
                        count = file.Read(buffer, 0, bufferSize);
                    }
                    else
                    {
                        count = -1;
                    }
                }
                this.Page.Response.End();
            }
        }
    }

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:4)

您没有在Response上设置ContentType属性。尝试将ContentType设置为image/x-icon(请注意,“正确”的内容类型可能为image/vnd.microsoft.icon,但this post似乎表明您可能遇到此类问题)

代码应该类似于:

this.Page.Response.Clear();
this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
this.Page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20));
this.Page.Response.ContentType = "image/x-icon";