locked
split Method

    Question

  • How to use split method for retrieving Datasource name(myServerAddress)

    Myconnection.connetionstring=”Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword”;

    I used like this.....

    Myconnection.connetionstring=Myconnection.connetionstring.split(";")[1];

    But i did get the datasource name....Let me know where i have to change..

    Thanks,

    Kavitha

      



    kavitha
    Wednesday, December 21, 2011 4:40 PM

Answers

  • The parser for connection strings already exists. No need to reinvent the wheel:

    SqlConnectionStringBuilder csBuilder = new SqlConnectionStringBuilder(@"Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword");
    
    string dataSource = csBuilder.DataSource;
    

     

    Thursday, December 22, 2011 1:40 PM
  • Hi,

    Actually you should get an error when you write this code

    Myconnection.connetionstring=Myconnection.connetionstring.split(";")[1];

    because there is no overload method for Split method which accepts a string as param.

    Also since you are splitting based on ';' semi-colon,and you are interested in the first value you should get the index[0],beacuse arrays are zero-based indexed.

    So, you should modify your code as follows :

    Myconnection.connetionstring=Myconnection.connetionstring.Split(';')[0];

    This line gives you the value as "Data Source=myServerAddress".Now you can retrieve the value using following line

    string reqStr = Myconnection.connetionstring.Substring(Myconnection.connetionstring.IndexOf('=') + 1);

     

    -+-+-+-+-+-+-+-+-+-+-+-+

    Learn, Earn, Enjoy..!


    Thanks, Satish Bommideni
    Thursday, December 22, 2011 3:47 AM

All replies

  • Hi kavitha,

                   Try this,

    string connectionstring=”Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword”;
    
    string[] split = connectionstring.Split(new Char[] { ";" });
    
    
    Interaction.MsgBox(GetDataSourceName(split));
    
    private string GetDataSourceName(string[] split)
    {
    
    	foreach (string s in split) {
    		// Check for empty space
    		if (!string.IsNullOrEmpty(s.Trim())) {
    			if (s.contains("Data source=")) {
    				return s.Remove(0, Strings.Len("Data source="));
    			}
    		}
    	}
    
    }
    


    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". Happy Coding...
    Wednesday, December 21, 2011 5:05 PM
  • Well, you can use more than 1 char separator.  Read this

    http://msdn.microsoft.com/en-us/library/b873y76a.aspx

    Regards

    Wednesday, December 21, 2011 5:10 PM
  • You can get your data source name by doing the following

     

    string s = MyConnection.connectionstring.Split(";")[0].Split("=")[1];
    


     

    but I would suggest a more robust route

     

    string s;
    string[] myStrings = Myconnection.connetionstring.split(";");
    foreach(string str in myStrings)
    {
         string[] strsplit = str.split("=");
         if(strsplit.length >=2 && strsplit[0] == "Data Source")
              s = strsplit[1];
    }
    


     



    Wednesday, December 21, 2011 5:39 PM
  • @Samuel as per my post and the MSDN docs, you don't need to use Split twice, you can give it more than one char delimiter, read the link.

    Regards

    Wednesday, December 21, 2011 5:42 PM
  • Split is a fine method, but you also want to tokenize the output. That is where regular expression parsing shines. Here I find a match of the pattern "key=value;" and tokenize it into named fields of Key and Value. There I put it into a dictionary for easy extraction of the values.

     

    string data = @"Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword";
    
    string pattern = @"
    (?<Key>[^=]+)    # Put the first text into the Key capture group
    (?:\=\s*)        # Match but don't capture the = and any space
    (?<Value>[^;]+)  # Get all text til the end of string which is not a ;
    (?:;?)           # Match but don't capture a ; if it exists";
    
            // IgnorePatternWhitespace only applies to the pattern so we can comment it; not regex parsing!
    Regex.Matches( data, pattern, RegexOptions.IgnorePatternWhitespace )
             .OfType<Match>()
             .ToDictionary( mt => mt.Groups["Key"].Value, mt => mt.Groups["Value"].Value )
             .ToList() // To do the foreach below
             .ForEach( kvp => Console.WriteLine( "{0,-20} : {1}", kvp.Key, kvp.Value ) );
            
    /* Output Data Source : myServerAddress Initial Catalog : myDataBase Integrated Security : SSPI User ID : myDomain\myUsername Password : myPassword */

     

    HTH

    Check out our MSDN .Net Regular expression Forums for specific regular expression questions. Here are some helful links:


    William Wegerson (www.OmegaCoder.Com)
    Wednesday, December 21, 2011 6:48 PM
  • Hi,

    Actually you should get an error when you write this code

    Myconnection.connetionstring=Myconnection.connetionstring.split(";")[1];

    because there is no overload method for Split method which accepts a string as param.

    Also since you are splitting based on ';' semi-colon,and you are interested in the first value you should get the index[0],beacuse arrays are zero-based indexed.

    So, you should modify your code as follows :

    Myconnection.connetionstring=Myconnection.connetionstring.Split(';')[0];

    This line gives you the value as "Data Source=myServerAddress".Now you can retrieve the value using following line

    string reqStr = Myconnection.connetionstring.Substring(Myconnection.connetionstring.IndexOf('=') + 1);

     

    -+-+-+-+-+-+-+-+-+-+-+-+

    Learn, Earn, Enjoy..!


    Thanks, Satish Bommideni
    Thursday, December 22, 2011 3:47 AM
  • The parser for connection strings already exists. No need to reinvent the wheel:

    SqlConnectionStringBuilder csBuilder = new SqlConnectionStringBuilder(@"Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword");
    
    string dataSource = csBuilder.DataSource;
    

     

    Thursday, December 22, 2011 1:40 PM