http://aspsnippets.com/Articles/Implement-Role-based-security-Page-access-and-ShowHide-Menu-items-based-on-Role-in-ASPNet.aspx
Please download the Sample from the above link.
Please refer this code to add Or Delete Roles.
HTML
<h1>
Home</h1>
<br />
<asp:DropDownList ID="ddlRoleTypes" runat="server">
<asp:ListItem Text="Allow" />
<asp:ListItem Text="Deny" />
</asp:DropDownList>
<br />
Roles
<asp:TextBox ID="txtRoles" runat="server" />
<br />
Add Roles
<br />
<asp:Button ID="btnAddRoles" runat="server" Text="Add Roles" OnClick="AddRoles" />
<br />
Delete Role by name
<br />
<asp:TextBox ID="txtDeleteRoles" runat="server" />
<br />
<asp:Button Text="Delete Role" ID="btnDeleteRoles" OnClick="DeleteRole" runat="server" />
Namespace
using System.Web.Security;
using System.Xml;
using System.Web.Configuration;
C#
protected void AddRoles(object sender, EventArgs e)
{
string path = Server.MapPath("~/Web.Config");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlNodeList list = xDoc.DocumentElement.SelectNodes("system.web/authorization");
if (list.Count > 0)
{
XmlElement newAllowelement = xDoc.CreateElement("allow");
XmlAttribute newAllowAttrib = xDoc.CreateAttribute("roles");
AuthorizationRule newRule;
if (this.ddlRoleTypes.SelectedItem.Value == "Allow")
{
newRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
}
else
{
newRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
}
newRule.Roles.Add(ddlRoleTypes.SelectedItem.Value).ToString();
newAllowAttrib.Value = this.txtRoles.Text.Trim();
newAllowelement.Attributes.Append(newAllowAttrib);
list[0].AppendChild(newAllowelement);
xDoc.PreserveWhitespace = true;
//write to web.config file using xml writer
XmlTextWriter xwriter = new XmlTextWriter(path, null);
xDoc.WriteTo(xwriter);
xwriter.Close();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please add authorization under system.web Node in Web config file')", true);
}
}
protected void DeleteRole(object sender, EventArgs e)
{
string path = Server.MapPath("~/Web.Config");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlNodeList list = xDoc.DocumentElement.SelectNodes("system.web/authorization");
if (list.Count > 0)
{
for (int i = 0; i < list[0].ChildNodes.Count; i++)
{
if (list[0].ChildNodes[i].Name == "allow")
{
if (list[0].ChildNodes[i].Attributes["roles"].Value == txtDeleteRoles.Text)
{
list[0].ChildNodes[i].ParentNode.RemoveChild(list[0].ChildNodes[i]);
xDoc.PreserveWhitespace = true;
XmlTextWriter xwriter = new XmlTextWriter(path, null);
xDoc.WriteTo(xwriter);
xwriter.Close();
}
}
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('No Role found!')", true);
}
}
}