0

New to C# programming, and I'm kind of stuck right now. How would I create a simple program that let's me extract and display the data source value in connectionStrings. And lets me modify the Id and password? Am I on the right track with parsing

Document X = XDocument.Load("C:\Users\Odd_Creature\Desktop\SecureConfig\\UserProfiles\UserInfo.exe.config")

    var configuration= X.Element("configuration").Element("connectionStrings");
    var location = configuration.Descendants("").Attributes("").FirstOrDefault().Value;
doc.Save(xmlfile);

XMLFILE

<configuration>
      <configProtectedData />
      <system.diagnostics />
      <system.windows.forms />
      <uri />
      <appSettings>
        <add key="GenerateProfile" value="true" />
        <add key="TestScore" value="30" />
        <add key="TestApplicationName" value="User Account" />
      </appSettings>
      <connectionStrings>
        <add name="MyExample.database" connectionString="data source=.\SQLEXPRESS;initial catalog=wadb;integrated security=false;encrypt=true;trustservercertificate=true;User Id=Tester;Password=Test1;"
          providerName="System.Data.SqlClient" />
      </connectionStrings>
Masterolu
  • 471
  • 1
  • 8
  • 19

1 Answers1

0

This would be a brute force approach to parsing the connection string from an XML file.

    static void Main(string[] args)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("settings.xml");

        string connectionStrings = xmlDoc.GetElementsByTagName("connectionStrings")[0].InnerXml;

        string tag = "connectionString=\"";
        string connectionString = connectionStrings.Substring(connectionStrings.IndexOf(tag) + tag.Length);

        string[] tokens = connectionString.Split(';');
        Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("data source=")));
        Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("User Id=")));
        Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("Password=")));
    }

And the output would be:

data source=.\SQLEXPRESS

User Id=Tester

Password=Test1

With a little more code, you should be able to edit these fields, and then use xmlDoc.Save() to update your changes.

Jason D
  • 1,863
  • 2
  • 16
  • 30