@manhnguyenv

Welcome to my blog!

Save Session Timeout in Web.config as XML Document

January 3, 2020 12:06

Save Session Timeout in Web.config as XML Document (edit)

using System;
using System.Diagnostics;
using System.IO;
using System.Xml;

namespace ConsoleApp11
{
public class Program
{
public static void Main(string[] args)
{
string webConfigFilePath = @"C:\inetpub\wwwroot\WebApp\web.config";

bool isSaveSuccess = SaveSessionTimeoutToWebConfig(webConfigFilePath, "480");
}

public static bool SaveSessionTimeoutToWebConfig(string filePathWebConfig, string sessionTimeout)
{
//
// Change timeout from 30 to 1440
// FROM: <sessionState timeout="30" />
// TO: <sessionState timeout="1440" />
// ----------
// FROM:
//<authentication mode="Forms">
// <forms name="WebApp.CookieName" loginUrl="~/Login.aspx" protection="All" timeout="30" path="/" requireSSL="true" slidingExpiration="true" enableCrossAppRedirects="false" cookieless="UseDeviceProfile"></forms>
//</authentication>
// TO:
//<authentication mode="Forms">
// <forms name="WebApp.CookieName" loginUrl="~/Login.aspx" protection="All" timeout="1440" path="/" requireSSL="true" slidingExpiration="true" enableCrossAppRedirects="false" cookieless="UseDeviceProfile"></forms>
//</authentication>

try
{
if (File.Exists(filePathWebConfig))
{
XmlDocument doc = new XmlDocument();
doc.Load(filePathWebConfig);

XmlNode sessionState = doc.DocumentElement.SelectSingleNode("//system.web//sessionState");

if (sessionState != null)
{
if (sessionState.Attributes["timeout"] != null && sessionState.Attributes["timeout"].Value == sessionTimeout)
{
//return true;
}
else
{
sessionState.Attributes["timeout"].Value = sessionTimeout;
doc.Save(filePathWebConfig);
}
}

XmlNode formsAuthentication = doc.DocumentElement.SelectSingleNode("//system.web//authentication//forms");

if (formsAuthentication != null)
{
if (formsAuthentication.Attributes["timeout"] != null && formsAuthentication.Attributes["timeout"].Value == sessionTimeout)
{
return true;
}
else
{
formsAuthentication.Attributes["timeout"].Value = sessionTimeout;
doc.Save(filePathWebConfig);
}
}
}
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}
}
}
}

Categories

Recent posts