2013-05-10 13 views
7

Próba sprawdzenia, czy plik istnieje wewnątrz ścieżki, ale pojawia się błąd kompilacji w pliku.Plik jest metodą, która jest niepoprawna w danym kontekście.

Plik jest metodą i nie można go używać w tym kontekście.

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

Pełny kod klasy

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

Jak można rozwiązać ten problem?

+0

musisz podać błąd –

+0

Oczywiście, przepraszam edytowane. – b0w3rb0w3r

Odpowiedz

41

Prawdopodobnie masz tę metodę wewnątrz kontrolera MVC, w którym istnieje metoda pliku. Dodaj swój kod System.IO.File zamiast File

+1

Naprawiono to dzięki. – b0w3rb0w3r

+0

Naprawiłem też ... –

Powiązane problemy