MVC 应用程序部署到服务器后,CSV 文件无法导入

CSV file fails to import once MVC Application deployed to Server

我可能面临一个非常明显的问题,但我找不到解决方案。我正在将数据从 CSV 文件导入到我的 SQL 数据库 - 这在我的开发环境中工作得很好,但一旦部署到我们的专用服务器就无法工作(这是临时测试,它将被移动到一个网络服务器我只有 ftp 访问权限,所以无法在任何一个上安装任何东西。

这是我的代码:

public ActionResult ImportExcel(PipelineDetails model, HttpPostedFileBase FileUpload, int ProjectID)
    {
        string Result = "";
        string UploadfileSaved_Path;
        ProjectManager PM = new ProjectManager();
        PipelineData PD = new PipelineData();

        try
        {
            if (!FileUpload.FileName.EndsWith("csv"))
            {
                Result = "File type not allowed. Please import file using CSV format(Comma Delimited).";
                return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
            }

            string[] lines = System.IO.File.ReadAllLines(FileUpload.FileName);
            bool isHeader = true;
            int i = 0;

            foreach (string line in lines)
            {

                string[] col = line.Split(new char[] { ',' });

                if (i >= 1)
                {
                    isHeader = false;
                }
                else
                {
                    if (col[0] != "Accumulated_Length" || col[1] != "Elevation" || col[2] != "Pipe_Outside_Diameter" ||
                                    col[3] != "Wall_Thickness")
                    {
                        Result = "Import files Headers are incorrect. Please correct before retrying.";
                        return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
                    }
                }

                if (col[0] == null || col[1] == null || col[2] == null || col[3] == null)
                {
                    Result = "Some values are missing in the Import File. Please check the data.";
                    return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
                }

                if (!isHeader)
                {
                    if (i == 1)
                    {

                        PM.DeleteALLPipeLine_forProject(ProjectID);
                    }

                    using (RexusTradingEntities RTE = new RexusTradingEntities())
                    {
                        PD.Accumulated_Length = Convert.ToDecimal(col[0]);
                        PD.Elevation = Convert.ToDecimal(col[1]);
                        PD.Pipe_Outside_Diameter = Convert.ToDecimal(col[2]);
                        PD.Wall_Thickness = Convert.ToDecimal(col[3]);

                        if (col[4] != "" && col[4] != null)
                        {
                            PD.Control_Point_Description = col[4];
                        }

                        if (col[5] != "" && col[5] != null)
                        {
                            PD.Control_Point_Size = Convert.ToDecimal(col[5]);
                        }

                        PD.fkiProjectID = ProjectID;
                        PD.CreateDateTimeStamp = DateTime.Now;

                        RTE.PipelineDatas.Add(PD);
                        RTE.SaveChanges();
                    }
                }

                i++;
            }
        }
        catch (Exception ex)
        {
            //Result = "There is a problem with the Import File. Please check the file format or data.";
            Result = ex.Message + " : " + FileUpload.FileName;
            return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
        }

        //Adding the Node Numbers in sequencial order
        PM.UpdatePipelineNodeNumbers(ProjectID, model);

        Result = "Import Success";

        return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
    }

我得到的错误是:'Could not find file 'C:\Windows\SysWOW64\inetsrv\RexusImportTemplate.csv'

现在这看起来很明显(找不到文件),我正在使用一个对话框,我 select 我的电脑上的文件(其他人会在他们的电脑上做),所以我不需要保存文件(除非我必须这样做,否则我什至有权限)。

我试过使用 FileUpload.SaveAs(FileUpload.FileName) 但后来我得到一个错误,这个 saveas 只允许保存在根目录中。然后我尝试了 FileUpload.SaveAs("~/" + FileUpload.FileName),这表示我无权访问该文件夹...

我认为文件将从指定的路径读取,而不是从部署 Web 应用程序的服务器上的路径...?

我已经为此苦苦挣扎了一段时间 - 是否有任何人知道的解决方法?

提前致谢!

我认为您需要在服务器上映射路径。 Server.MapPath(PathWhereFilesWillBeSaved) 能够将文件保存在服务器上的项目目录中。 MSDN - Server.MapPath

两件事:

  • 确保使用 FileUpload.HasFile() (MSDN Link)
  • 检查文件是否存在
  • 使用 Server.MapPath(filename) (MSDN Link) 确保在 saving/reading.
  • 时映射到当前应用程序的目录

当你运行

System.IO.File.ReadAllLines(FileUpload.FileName)

您是在告诉 .net 从文件系统中读取与上传文件同名的文件,而不是用户上传的文件。

如果要将文件保存到本地,请在使用 SaveAs 方法之前尝试将路径映射到要保存到的位置(可能 App_Data):

public ActionResult Index(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
    //read your file's contents here
  }

  return RedirectToAction("Index");
}

取自http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/