2013-02-18 62 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);