public static  void DownloadFile(string fileName,string showName)
{
string physicalFilePath = GetDianDanHeTongImagePath()+@"\"+fileName;
FileStream stream=null;
try 
{
stream = new FileStream(physicalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
int bufSize = (int)stream.Length;
byte[] buf = new byte[bufSize];
int bytesRead = stream.Read(buf, 0, bufSize);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition","attachment; filename=\"" + HttpUtility.UrlEncode(showName,System.Text.Encoding.UTF8) + "\"");
HttpContext.Current.Response.OutputStream.Write(buf, 0, bytesRead);
HttpContext.Current.Response.End();
stream.Close();
}
finally {                                                                                                                  

}
}文件存在局网服务器下,为什么执行到
HttpContext.Current.Response.ContentType 的时候就说:未将对像引用到实例呢?

解决方案 »

  1.   

    因为你的Response是null
    建议你用webclient来做,它有DownloadData(path)和OpenRead(path)方法
      

  2.   

    谢谢楼上,我的方法已经实现了,贴出代码,以备后来来查:System.Windows.Forms.SaveFileDialog saveFile = new SaveFileDialog();
    saveFile.Filter = "*.tif|*.TIF|*.jpg|*.JPG|*.gif|*.GIF";
    string SourceURL = CRM.Sys.Utility.CommonFun.GetDianDanHeTongImagePath()+@"\"+fileName;
    DialogResult result = saveFile.ShowDialog();
    //saveFile.
    if(result ==DialogResult.Cancel)
    return;
    string DestPath = saveFile.FileName;
    System.Net.WebClient webClient=new System.Net.WebClient();
    Stream stream = webClient.OpenRead(SourceURL);
    byte[] arrByte = new byte[1024];
    long completedByteCount = 0;
    if (File.Exists(DestPath))
    File.Delete(DestPath);
    FileStream fStream = new FileStream(DestPath,FileMode.CreateNew,FileAccess.Write);
    while(true)
    {
    int readCnt = stream.Read(arrByte,0,1024);
    if(readCnt==0) 
    break;      
    fStream.Write(arrByte,0,readCnt);
    completedByteCount += readCnt;
    }              
    stream.Close();
    fStream.Close();///不过现在有一个小问题时,在弹出SaveFileDialog的时候,我不知如何初始化"保存文件的名字"