SharePoint provides classes that help you work with Web.config entries for your solution in a robust  and simple way. Whenever your solutions need to add, edit, or retrieve Web.config entries, use these  classes, rather than creating your own approaches for working with Web.config files.
This article, I would like to show you

  • Describe the relationship between Web.config files and SharePoint Web applications in a multi-server  farm environment.
  • Add Web.config entries programmatically by using the SharePoint object model.
  • Retrieve and use Web.config entries in your solution code

Overview

Web.config entries for a SharePoint Web application affect all site collections in that Web application.

Web.config entries need to be propagated to all Web servers in a SharePoint farm. The SharePoint object model does this for you.
A SharePoint Web Application (SPWebApplication) is analogous to a traditional IIS Web site. In fact, when you create a Web application by using the SharePoint Central Administration application, an IIS Web site is automatically created. You can verify that the IIS Web site has been created by looking in IIS Manager, where you can see its structure, Web.config file, and virtual directory mappings. The Web.config file contains the settings required by the SharePoint Web application, just as that file would do for ASP.NET Web sites.

The settings in the Web.config file affect all site collections, sites, and sub-sites in the SharePoint Web application. Therefore, you must be careful when editing Web.config, as changes normally have farreaching implications.

Below code snippet will show you how to work with App setting for add and modify an keyname

void AddAndModifyKeyName(bool status)
{ 
	SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://SharePoint"));
	try
	{ 
		SPWebConfigModification mySetting = null;
		if (status)
		{ 
			mySetting = new SPWebConfigModification(); 
			mySetting.Path = "configuration/appSettings";
			mySetting.Name = "add [@key='yourkeyname'] [@value='1']";
			mySetting.Sequence = 0;
			mySetting.Owner = "Yourname";
			mySetting.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
			mySetting.Value = "";
			webApp.WebConfigModifications.Add(mySetting);
		} 
		else
		{ 
			foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
			{ 
				if (modification.Owner == "Yourname")
				{ 
					modification.Value = "";
				} 
			} 
		} 
		webApp.Update();
		webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
	} 
	catch
	{ 
	} 
} 

 

Hoang Nhut NGUYEN