【问题标题】:How do I save a file to disk?如何将文件保存到磁盘?
【发布时间】:2011-02-25 00:09:25
【问题描述】:

这是我的控制器:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase excelFile)
    {

        /*Somewhere here, I have to save the uploaded file.*/

        var fileName = string.Format("{0}\\{1}", Directory.GetCurrentDirectory(), excelFile.FileName);
        var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

        var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
        var ds = new DataSet();
        adapter.Fill(ds, "results");

        DataTable data = ds.Tables["results"];

        return View();
    }

【问题讨论】:

  • 你到底想保存什么到磁盘?
  • excelFile 是上传到网站的文件。 .xlsx 文件。我需要将该文件永久保存到硬盘驱动器。我猜使用 .InputStream 属性?但我对如何做到这一点感到困惑。
  • 如果您只是想知道如何保存 excelFile,我们不需要与数据库对话的其余代码 - 这很令人困惑。只需提供最少量的代码。

标签: c# file save


【解决方案1】:

如果您正在接收上传的文件,这是一种处理方式。

string nameAndLocation = "~/UploadedFiles/" + hpf.FileName;
hpf.SaveAs(Server.MapPath(nameAndLocation));

【讨论】:

  • 我想他是在问关于专门保存 excelFile 的问题。
  • 谢谢,这有点帮助。 :)
【解决方案2】:

你试过HttpPostedFileBase.SaveAs方法吗?

【讨论】:

  • 我没有看到那个方法。 :) 只是一个问题,如果我只给它一个要使用的文件名,它会将文件保存在哪里?
  • 如果只指定文件名,则将当前目录作为文件的位置。您可能更喜欢不使用 Directory.GetCurrentDirectory,而是使用 Server.MapPath 将您网站中的某些相对路径映射到物理路径。例如,Server.MapPath(@"~/ExcelFiles/data.xls")
【解决方案3】:
[HttpPost]
public ActionResult Index(HttpPostedFileBase excelFile)
{
   /*Somewhere here, I have to save the uploaded file.*/

   var fileName = string.Format("{0}\\{1}", Directory.GetCurrentDirectory(), excelFile.FileName);

   excelFile.SaveAs(fileName );

   //...
}

如有疑问,请查看文档: http://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.saveas.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2013-12-19
    • 2010-09-23
    • 2010-11-08
    • 2021-11-03
    • 2019-10-30
    • 2018-01-13
    相关资源
    最近更新 更多