如何将文件保存到磁盘?

时间:2011-02-25 00:09:25

标签: c# file save

这是我的控制器:

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

3 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:5)

您是否尝试过HttpPostedFileBase.SaveAs方法?

答案 2 :(得分: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