2

Im sitting with possibly a very obvious issue that I can not find a solution to. I am Importing data from a CSV file to my SQL DB - This works perfect in my Development environment, but wont work once deployed to our Dedicated server(This is temporary for testing, which will be moved to a web server that I only have ftp access to, so cant install anything on either).

Here is my code :

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

And the error I am getting is : 'Could not find file 'C:\Windows\SysWOW64\inetsrv\RexusImportTemplate.csv'

Now as obvious as this may seem(File not found), I am using a dialog where I select the file on my pc(and other will do on their pcs), so I dont require to save the file(unless I have to, if ill even have permissions).

I Tried using FileUpload.SaveAs(FileUpload.FileName) but then I got an error that this saveas only allows to be saved in the root. Then I tried FileUpload.SaveAs("~/" + FileUpload.FileName) and this said I dont have access to the folder...

I thought that the file will be read from the path specified, rather than a path on the server where the Web Application was deployed... ?

I have been struggling on this for a while now - are there any work arounds that anyone is aware of ?

Thanks in advance!

3 Answers 3

1

I think you need to map the path on the server. Server.MapPath(PathWhereFilesWillBeSaved) to be able to save files in your project directory on a server. MSDN - Server.MapPath

Sign up to request clarification or add additional context in comments.

Comments

1

Two things:

  • Make sure you do check if the file exists by using FileUpload.HasFile() (MSDN Link)
  • Use Server.MapPath(filename) (MSDN Link) to ensure you are mapping to the current application's directory when saving/reading.

4 Comments

Thanks for the reply. The file does exist on my local, but not on the server where the application is located. Does it need to, to import ? I tried the following : FileUpload.SaveAs(Server.MapPath("~/") + FileUpload.FileName) and I got the following error : Access to the path 'C:\inetpub\wwwroot\SCF\AirFlo\RexusImportTemplate.csv' is denied.
@AxleWack: You probably need to create a valid path; Path.Combine(Server.MapPath(PathToFileDirectory), FileUpload.FileName); This has worked for me in the past when getting files to and from my application directory on a server.
@Ingenioushax I had a valid path, but the problem was access rights - Which is the problem if I dont have access to the server myself to provide read/write access to the specific older :( I have requested for this now, so I hope they will... Thanks in any case.
@AxleWack: Ahh yes, the infamous permissions. Good luck!
0

When you run

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

You're telling .net to read a file from the filesystem with the same filename as the file uploaded, not the file the user uploaded.

If you want to save the file locally, try to map the path to the location you want to save it to (possibly App_Data) before using SaveAs method:

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

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

4 Comments

Thanks for the reply. I will check this out quick and let you know what my results are.
Gave it a try and access is denied : Access to the path 'C:\inetpub\wwwroot\SCF\AirFlo\App_Data\Upload\RexusImportTemplate.csv' is denied
So I got it to work, but only if I provide read/write access to the App_Data folder - Which is great and all that it works, but I might sit with the same issue when I finally FTP to the clients web server... damn. Thanks in anycase. Will mark your answer as the answer.
Well, if you need to save files locally (and don't have any application/database to use for storage) then you will need access to a local filesystem location...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.