# Error on SPWebApplication.WebService.ApplyWeyConfigModifications

I've been trying to add a line to my web.config through a EventReceiver on my webpart's Feature. I tried to follow some 'tutorials' (this, this and this). It wasn't working, but at least i could deploy the solution.

Sometimes it would delete everything on my web.config and leave only the line that i wanted to add. It was a simple line on <configuration><appSettings><add key="searchPath" value="http://myVirtualMachineSearchPath" />

After the update, it would leave me empty with just that one single line on the web.config.

Right now, my code is this:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
InsertWebConfigEntries(properties);
}

{
if (!CheckEntries(properties))
{
using (SPSite site = properties.Feature.Parent as SPSite)
{
SPWebConfigModification dsEntry = GenerateWebConfigEntry("New config key", "configuration/appSettings",

SPWebApplication currentWebApp = site.WebApplication;

currentWebApp.WebService.ApplyWebConfigModifications();
currentWebApp.Update();
}
}
}

//check if the web.config entry exists. If you don't call this method you will get duplicate entries
{
using (SPSite site = properties.Feature.Parent as SPSite)
{
SPWebApplication currentWebApp = site.WebApplication;

Collection<SPWebConfigModification> webConfigEntries = currentWebApp.WebConfigModifications;

foreach (SPWebConfigModification entry in webConfigEntries)
{
if (entry.Owner == "Owner")
{
return true;
}
}

return false;
}
}

//new web.config entry
private SPWebConfigModification GenerateWebConfigEntry(string modName, string sXpath, string sKey, uint iSequence)
{
SPWebConfigModification configMod = new SPWebConfigModification(modName, sXpath);
configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
configMod.Owner = "Owner";

configMod.Value = sKey;
configMod.Sequence = iSequence;

return configMod;
}


But now, when I try to deploy the solution, it gives me an error:

Error occurred in deployment step 'Activate Features': Failed to apply web.config modifications to Web application '3f79bb09-9e0f-4aed-a400-5debe6346440'.
Failed to apply web.config modifications to file 'C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config'.
Failed to apply a web.config modification to file 'C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config'.

When i debug the code, my SPWebApplication.WebConfigModifications already contains 18 elements that i added on my previous attempts, but i deleted that code and for some reason, i can't evoke the WebConfigModifications.Clear() method with success, every time i try to use the SPWebApplication.Update() it gives me the error above, even when i don't add any other SPWebConfigModification.