Search code examples
c#data-driven-testsdata-driven

OledbConnection Invalid Arguments


I try to read Excel file in Selenium Webdriver C# but got Invalid Arguments at connection.Open() . What am I wrong?

using System.Configuration;
using System.Data.OleDb;
using System.Linq;

namespace LeTuanAnh_Training.TestDataAccess
{
    class ExcelDataAccess
    {
        public static string TestDataFileConnection()
        {
            var fileName = ConfigurationManager.AppSettings["TestDataSheetPath"];
            var con = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = {0}; Extended Properties=Excel 12.0;", fileName);
            return con;
        }

        public static UserData GetTestData(string keyName)
        {
            using (var connection = new OleDbConnection(TestDataFileConnection()))
            {
                connection.Open();
                var query = string.Format("select * from [Sheet1$] where key='{0}'", keyName);
                var value = connection.Query<UserData>(query).FirstOrDefault();
                connection.Close();
                return value;
            }
        }
    }
}

App.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings configSource="Configurations\Environment.config" />
</configuration>

Environment.config file

<?xml version="1.0" encoding="utf-8" ?>
    <appSettings>
      <add key="TestDataSheetPath" value="TestDataAccess/Data.xlsx"/>
</appSettings>

Error Pic


Solution

  • When you are doing

    using (var connection = new OleDbConnection(TestDataFileConnection()))
    

    The Using keyword open the connection and closes it when the using block ends. So you don't need the connection.Open() and the connection.Close().

    Try to connect to your DB and double-check the DB connection data. Your question has nothing to do with Selenium...