Jeff Jeff - 4 months ago 32
C# Question

Best practice for peristantly storing a string on a C# IIS WCF web service

I have a text string I want to persist in a WCF web service. What is the best practice for storing it between sessions and between reboots/restarts of IIS?

Storing it in a text file on the operating system? Or is there a built in persistence object?

This string is a piece of text I need to return from the web service and occasionally update via a call being made to the web service. (The web service has a Read Only database back end, so I don't have the option to save this string to a database--without adding a separate database call and I'd rather avoid that extra point of failure.)

You mean a connection string? web.config
Or a password, or key? web.config
Something that's displayed to the user? resource table

P.s. I ended up using the web.config solution. For those interested in doing what I did here's the hoops I jumped through:

1) Set up a directory under the web application's root and opened that up to write permission to the IISUser. (Used a sub directory to avoid compromising security in the main application directory) Then added the following to the top of my source code:

System.Configuration.Configuration _webConfig = 

2) Namespaces needed:

using System.Web.Configuration;
using System.Configuration;

3) Code to create a new setting. The try/catch handles when the setting doesn't exist. Yes, it's a total hack. If someone knows how to check for the existence of the setting please let me know in a comment!

        _webConfig.AppSettings.Settings["SettingName"].Value = textMessage;
    } catch {
        _webConfig.AppSettings.Settings.Add("SettingName", textMessage);

4) Code to read:

TextMessage = _webConfig.AppSettings.Settings["SettingName"].Value;


You can do something like:

        bool bKeyExists = false;

        foreach (SettingsProperty settingsProperty in appSettings.Properties)
            if (settingsProperty.Name == _strKey)
                bKeyExists = true;