使用Server.MapPath保存文件

时间:2013-06-03 09:18:18

标签: asp.net file-upload

目前,我正在将文件保存到我的代码中硬编码的目录中:

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

但我需要使用Server.MapPath保存我的文件.... 喜欢:

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

完整的功能:

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

但是当我尝试使用Server.MapPath("~/App_Data/stored")时,它不知道服务器是什么

修改

我可以像HttpContext.Current.Server.MapPath("~/App_Data/stored");一样使用它 但我不能像package.Id + ".zip"

那样使用var savePath = HttpContext.Current.Server.MapPath("~/App_Data/stored"),package.Id + ".zip"));

2 个答案:

答案 0 :(得分:4)

您可以通过当前上下文HttpContext.Current.Server.MapPath("~/App_Data/stored");

访问它

获取完整文件路径:

var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/stored"), package.Id + ".zip");

答案 1 :(得分:-1)

            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            if (fileName != "")
            {

                FileUpload1.SaveAs(Server.MapPath("../../Files/" + fileName));
                aComplain.FileName = fileName;
                aComplain.FilePath = "../../Files/" + fileName;

                string message = aComplainManager.SaveComplain(aComplain);
                messageResult.Text = message;
                messageResult.ForeColor = Color.Green;
                Clear();
            }

            else if (fileName == "")
            {
                string message = aComplainManager.SaveComplain(aComplain);
                messageResult.Text = message;
                messageResult.ForeColor = Color.Green;
                Clear();
            }