0

我正在使用此代码下载我的解决方案中存在的 excel 文件。我添加了一个文件夹 FileUpload 并添加了一个 Excel 文件 UploadCWF.xlsx。我的代码在本地主机上运行。但是当我将它托管到服务器时不起作用。我收到错误 - 找不到路径的一部分。我的代码 -

        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);

请有人帮助我。

4

1 回答 1

4

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

你应该写这样的代码

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

 System.IO.FileInfo FileName = new System.IO.FileInfo(filePath);
于 2013-02-18T05:57:25.827 回答