As @yonsk already mentioned why this problem occurs (duplicate entry of ), you can create a console application which can fix the machine.config file and then, invoke that console application from your Application's Installer or from your Application whenever you get the Exception. The following code can be used for the console application that will fix the machine.config file.
class Program
{
static void Main()
{
string machineConfigFilePath = RuntimeEnvironment.SystemConfigurationFile;
XDocument xdoc = XDocument.Load(machineConfigFilePath);
XElement[] elements = xdoc.XPathSelectElements("//configuration/system.data/DbProviderFactories").ToArray();
if (elements.Any())
{
foreach (XElement anElement in elements)
{
if (!anElement.HasElements)
anElement.Remove();
}
}
xdoc.Save(machineConfigFilePath);
}
}
If you want to call the console application, from your Application, you would need to invoke that as Administrator. So, the following snippet may help to invoke that console application as Administrator (The user will be prompted with a dialog to accept..)
try
{
Process process = Process.Start(new ProcessStartInfo
{
Verb = "runas",
FileName = "/Path/to/the/console/application",
UseShellExecute = true,
CreateNoWindow = true,
});
process.WaitForExit();
int exitCode = process.ExitCode;
}
catch (Exception ex)
{
}