2013-05-10 60 views
7

嘗試檢查文件中是否存在文件但在文件上發生構建錯誤。文件是一種在給定的上下文中無效的方法

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

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

怎樣才能解決這個問題?

+0

您將需要提供錯誤 – 2013-05-10 04:46:53

+0

Ofcourse,抱歉編輯。 – b0w3rb0w3r 2013-05-10 04:51:23

回答

41

您可能在File方法存在的MVC控制器內部有此方法。加入您的代碼System.IO.File而不是File

+1

這解決了它,謝謝。 – b0w3rb0w3r 2013-05-10 05:04:23

+0

這也固定了我... – 2016-12-30 05:04:58

相關問題