【问题标题】:File is a Method which is not valid in the given context [duplicate]文件是在给定上下文中无效的方法[重复]
【发布时间】:2013-05-10 13:43:28
【问题描述】:

尝试检查文件是否存在于路径中,但在 File 上出现构建错误。

文件是一种方法,不能在此上下文中使用。

 if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
        if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

完整类代码

 static void CovertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1)
    {
        if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
        if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

        // connection string
        var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
        var cnn = new System.Data.OleDb.OleDbConnection(cnnStr);

        // get schema, then data
        var dt = new DataTable();
        try
        {
            cnn.Open();
            var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
            string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
            string sql = String.Format("select * from [{0}]", worksheet);
            var da = new OleDbDataAdapter(sql, cnn);
            da.Fill(dt);
        }
        catch (Exception e)
        {
            // ???
            throw e;
        }
        finally
        {
            // free resources
            cnn.Close();
        }

        // write out CSV data
        using (var wtr = new StreamWriter(csvOutputFile))
        {
            foreach (DataRow row in dt.Rows)
            {
                bool firstLine = true;
                foreach (DataColumn col in dt.Columns)
                {
                    if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
                    var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
                    wtr.Write(String.Format("\"{0}\"", data));
                }
                wtr.WriteLine();
            }
        }
    }

如何解决这个问题?

【问题讨论】:

  • 您需要提供错误信息
  • 当然,抱歉编辑了。

标签: asp.net-mvc file-io


【解决方案1】:

你可能在 MVC 控制器中有这个方法,其中存在 File 方法。添加您的代码System.IO.File 而不是File

【讨论】:

  • 这已解决,谢谢。
  • 这也解决了我的问题...
  • 我不知道为什么,但它对我有用!!
  • 非常感谢,System.IO.File 有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2020-09-18
  • 2018-05-07
相关资源
最近更新 更多