Search code examples
asp.netconfigurationmanager

ASP.NET - Determine max file upload size at runtime


I have several places on my site where I have helptext telling users what the maximum allowed file upload size is. I would like to be able to have this be dynamic, so that if I change the request limits in the web.config file, that I don't have to go and change the form instructions in a bunch of places. Is this possible using ConfigurationManager or something?


Solution

  • Since you didn't give any further Details: As pointed out here, you have 2 options to set a size Limit for your whole Application.

    Depending on that you need to approach this a little differently:

    If you use <httpRuntime maxRequestLength="" /> you can get the Info through WebConfigurationManager

    //The null in OpenWebConfiguration(null) specifies that the standard web.config should be opened
    System.Configuration.Configuration root = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
    var httpRuntime = root.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection;
    int maxRequestLength = httpRuntime.MaxRequestLength;
    

    In Priciple you should be able to do the same with <requestLimits maxAllowedContentLength="" />. But the system.webServer-Section in WebConfigurationManager is declared as IgnoreSection and can't be accessed. It may be possible to change this behaviour in application.config or similiar of IIS. But since (in my case) even the .SectionInformation.GetRawXml() failed, I tend to declare this a lost case.

    My Solution in this case would be to access the Web.config-File manually:

    var webConfigFilePath = String.Format(@"{0}Web.config", HostingEnvironment.MapPath("~"));
    XDocument xml = XDocument.Load(System.IO.File.OpenRead(webConfigFilePath));
    string maxAllowedContentLength = xml.Root
        .Elements("system.webServer").First()
        .Elements("security").First()
        .Elements("requestFiltering").First()
        .Elements("requestLimits").First()
        .Attributes("maxAllowedContentLength").First().Value;
    

    Another Solution to this is proposed by @Roman here using Microsoft.Web.Administration.ServerManager for which you need the Microsoft.Web.Administration Package