2013-02-18 85 views
0

我正在使用此代码来下载我的解决方案中存在的excel文件。我添加了一个文件夹FileUpload并添加了一个Excel文件UploadCWF.xlsx。我的代码在本地主机上工作。但是,当我把这个服务器托管到服务器时不工作。我收到错误 - 无法找到路径的一部分。我的代码 -Server.map路径在asp.net中不工作

 string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/"); 
     string _DownloadableProductFileName = "UploadCWF.xlsx"; 

     System.IO.FileInfo FileName = new System.IO.FileInfo(filePath + "\\" + _DownloadableProductFileName); 
     FileStream myFile = new FileStream(filePath + "\\" + _DownloadableProductFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 

     //Reads file as binary values 
     BinaryReader _BinaryReader = new BinaryReader(myFile); 

     //Check whether file exists in specified location 
     if (FileName.Exists) 
     { 
      try 
      { 
       long startBytes = 0; 
       string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r"); 
       string _EncodedData = HttpUtility.UrlEncode(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp; 

       Response.Clear(); 
       Response.Buffer = false; 
       Response.AddHeader("Accept-Ranges", "bytes"); 
       Response.AppendHeader("ETag", "\"" + _EncodedData + "\""); 
       Response.AppendHeader("Last-Modified", lastUpdateTiemStamp); 
       Response.ContentType = "application/octet-stream"; 
       Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name); 
       Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString()); 
       Response.AddHeader("Connection", "Keep-Alive"); 
       Response.ContentEncoding = Encoding.UTF8; 

       //Send data 
       _BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin); 

       //Dividing the data in 1024 bytes package 
       int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0)/1024); 

       //Download in block of 1024 bytes 
       int i; 
       for (i = 0; i < maxCount && Response.IsClientConnected; i++) 
       { 
        Response.BinaryWrite(_BinaryReader.ReadBytes(1024)); 
        Response.Flush(); 
       } 
      } 
      catch (Exception es) 
      { 
       throw es; 
      } 
      finally 
      { 
       Response.End(); 
       _BinaryReader.Close(); 
       myFile.Close(); 
      } 
     } 
     else 

      System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), 
      "FileNotFoundWarning", "alert('File is not available now!')", true); 

请有人帮助我。

+1

你的代码是正确的。检查您是否将文件夹FileUpload添加到应用程序根目录。 – nunespascal 2013-02-18 05:45:48

+0

我已经将FileUpload文件夹添加到应用程序根目录。 – Gulrej 2013-02-18 05:53:14

回答

3

您应该首先concat文件路径和文件名,然后使用server.mappath获取路径。

你应该写这样的代码

string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/UploadCWF.xlsx"); 

System.IO.FileInfo FileName = new System.IO.FileInfo(filePath);