Using Server.MapPath to save a file

11,804

You can access it through the current context HttpContext.Current.Server.MapPath("~/App_Data/stored");

to get the full file path :

var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/stored"), package.Id + ".zip");
Share:
11,804
Java Afca
Author by

Java Afca

Updated on June 04, 2022

Comments

  • Java Afca
    Java Afca almost 2 years

    At the moment, I am saving my file to a directory hard coded in my code:

    var filePath = Path.Combine(@"C:\users\my documents\github\project\source\project\App_Data\stored\", package.Id + ".zip");
    

    But I need to save my file using Server.MapPath .... Like:

    FileInfo userFile = new FileInfo(Path.Combine(Server.MapPath("~/App_Data/stored"), package.Id));
    

    The complete function:

     public void CompressAndDeleteSources(FlinkeMailPackage package)
     {
        var filePath = Path.Combine(@"C:\users\my documents\github\project\source\project\App_Data\stored\", package.Id + ".zip");
    
        using (ZipFile zipFile = new ZipFile(filePath))
        {
          foreach (var file in package.FlinkeMailFileList)
          {               
            string bestandsNaam = @"C:\users\my documents\github\project\source\project\App_Data\uploads\" + file.OriginalName;
            zipFile.AddFile(bestandsNaam);
          }
           zipFile.Save();
        }
    
        foreach (var file in package.FlinkeMailFileList)
         {
             var filePathToDelete = @"C:\users\my documents\github\project\source\project\App_Data\uploads\" + file.FileName;
             File.Delete(filePathToDelete);
         }       
       }
    

    But when I am trying to use Server.MapPath("~/App_Data/stored") it doesn't know what server is

    EDIT

    I can use it like: HttpContext.Current.Server.MapPath("~/App_Data/stored"); But i can't use package.Id + ".zip" with it like example: var savePath = HttpContext.Current.Server.MapPath("~/App_Data/stored"),package.Id + ".zip"));

  • Java Afca
    Java Afca almost 11 years
    Ok, how can i use , package.Id + ".zip" with it. I can't use it like: var savePath = HttpContext.Current.Server.MapPath("~/App_Data/stored"), package.Id + ".zip"));