locked
Retrieving comma seperated list RRS feed

  • Question

  • Hi All,

    I have a App.Config file that has a key and value.  The value is in this format:

    'string1','string2','...','...'

    I want to retrieve this value from the config file and then split each string.  Each string is surrounded by 2 inverted commas ' ' and each string is seperated by commas.

    i.e. The result is a list of strings.

    Any ideas?
    Monday, September 8, 2008 10:46 AM

Answers

  • Try

    string old = ConfigurationManager.AppSettings[key];  
    string new = old.Replace("'","").split(','); 

    new is an string[] of split strings
    • Proposed as answer by Narotham Kalluri Monday, September 8, 2008 11:06 AM
    • Marked as answer by TheLearner Monday, September 8, 2008 11:14 AM
    Monday, September 8, 2008 11:06 AM

All replies

  • Try

    string old = ConfigurationManager.AppSettings[key];  
    string new = old.Replace("'","").split(','); 

    new is an string[] of split strings
    • Proposed as answer by Narotham Kalluri Monday, September 8, 2008 11:06 AM
    • Marked as answer by TheLearner Monday, September 8, 2008 11:14 AM
    Monday, September 8, 2008 11:06 AM
  • Can your quoted strings contain commas?  If not, then Narotham's answer (after fixing syntax errors) would work.

    However if your strings could contain commas or even escaped single-quotes (inverted commas?), you will need something more complex.

                // extract your value from key/value pair - test data follows
                string configFileValue = @"'abc','de\,f','gh\'i','klm','nop','qrs'";

                Regex rx = new Regex(@"(\'.*?\'(,|$))");
                Match mx = rx.Match(configFileValue);
                List<string> list = new List<string>();
                while(mx.Success)
                {
                    list.Add(mx.Value);
                    mx = mx.NextMatch();
                }
                string[] newString = list.ToArray();

    // Test the array
                foreach (string val in newString)
                    Console.WriteLine(val);

    Les Potter, Xalnix Corporation, Yet Another C# Blog
    Monday, September 8, 2008 11:45 AM