无法读取Excel文件 – File.open无效

我使用C#在.NET中构build一个小型网站。 用户必须上传已经实施的Excel文件,扩展名为.xls或.xlsx。 虽然我实际上从Excel文件读取值时遇到了麻烦。 我目前有这样的代码写出来:

public ActionResult Index(HttpPostedFileBase file) { string fileName = Path.GetFileName(file.FileName); if (fileName.EndsWith(".xlsx") || (fileName.EndsWith(".xls"))) { // store the file inside ~/App_Data/uploads folder string path = Path.Combine(Server.MapPath("~/App_Data/uploads/"), fileName); file.SaveAs(path); // Get file info int contentLength = file.ContentLength; string contentType = file.ContentType; // Get file data byte[] data = new byte[] { }; using (var binaryReader = new BinaryReader(file.InputStream)) { data = binaryReader.ReadBytes(file.ContentLength); } using (FileStream fs = File.Open(path, FileMode.OpenOrCreate)) { UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(data, 0, data.Length) > 0) { //Console.WriteLine(temp.GetString(b)); } } // redirect back to the index action to show the form once again return RedirectToAction("Index"); } 

现在我猜代码是不错的,但是我得到一个错误@第二个使用线,在'File.Open(…)'

 'System.Web.Mvc.Controller.File(byte[], string)' is a 'method', which is not valid in the given context C:\Users\.....cs 

我已经阅读了无数在线的例子,但没有一个似乎有类似的问题:/如果有人可以解决这个错误或帮助我解决这个问题,将不胜感激! 这可能是小/愚蠢的。

您的控制器类inheritance自System.Web.Mvc.Controller,它在基类“File”上有一个方法。 您需要在使用中明确使用正确的语句:

 using (FileStream fs = System.IO.File.Open(path, FileMode.OpenOrCreate))