Changing Stored Connection Strings and Application Settings at Runtime

Phill 61 Reputation points
2022-05-29T21:42:55.897+00:00

Hi All,

I have a quick question about Application settings inside the Project Properties. I just discovered that the settings are NOT editable at runtime but, I have some settings that would need to be saved via an application configuration form including many database parameters (server, user, password etc)

The settings are global to the application so they are not user scope. They need to be application scope. How would this be done if I did not know the login and server credentials on the end customers site?

Ideally, I would also encrypt the details inside the app.config file but, I don't know if this is possible when setting the settings at runtime.

Any help would be very much appreciated.

Developer technologies VB
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2022-05-30T05:36:47.967+00:00

    Hi @Phill ,
    You can refer to the documentation below.
    Access or change application settings at runtime in Visual Basic
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. LesHay 7,141 Reputation points
    2022-05-31T06:15:24.593+00:00

    Hi

    I can't reproduce the problem you are seeing.

    The values for the My.Settings.UserName is as expected here.
    Please check Project -> Properties -> Application -> Save My Settings on ShutDown

            '   My.Settings.Reset()
    
            MsgBox(My.Settings("UserName"))
            My.Settings("UserName") = "Test"
            MsgBox(My.Settings("UserName"))
    

  3. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-05-31T21:12:11.887+00:00

    See if this works for you, if it does than figure out an encryption/decryption methods to inject into the read and set operations. Yes it's not using My.Settings but it works.

    Full source

    Requires a reference to System.Configuration

    Option Infer On
    
    Imports System.Configuration
    Imports System.IO
    Imports System.Configuration.ConfigurationManager
    
    Public Class ApplicationSetting
        Public Shared Property ConnectionPath() As String = "AppConnectionString"
        Public Shared Sub SetConnection(ByVal sender As String)
            SetValue(ConnectionPath(), sender)
        End Sub
        Public Shared ReadOnly Property GetConnection() As String
            Get
                Return AppSettings(ConnectionPath())
            End Get
        End Property
        Public Shared Sub SetValue(key As String, value As String)
    
            Dim appName = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location)
    
            Dim configFile = Path.Combine(appName, $"{Reflection.Assembly.GetExecutingAssembly().GetName().Name}.exe.config")
    
            Dim configFileMap = New ExeConfigurationFileMap With {.ExeConfigFilename = configFile}
            Dim config = OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)
    
            If config.AppSettings.Settings(key) Is Nothing Then
                Throw New Exception($"Key {key} does not exist")
            End If
    
            config.AppSettings.Settings(key).Value = value
    
            config.Save()
    
            RefreshSection("appSettings")
    
        End Sub
    End Class
    

    Simple example

    Public Class Form1
        Private Sub GetButton_Click(sender As Object, e As EventArgs) Handles GetButton.Click
            Label1.Text = ApplicationSetting.GetConnection
        End Sub
    
        Private Sub SetButton_Click(sender As Object, e As EventArgs) Handles SetButton.Click
            ApplicationSetting.SetConnection(ConnectionStringTextBox.Text)
        End Sub
    End Class
    

  4. Phill 61 Reputation points
    2022-06-01T17:59:54.807+00:00

    HI All,

    After a lot of research, I am now able to write to the <ApplicationSettings> section of the .config file/settings per the code below however, now I have a new problem. When I run the program from the Program Files Directory, UAC is preventing me from being able to overwrite/save the changes.

    I know UAC exists for a good reason but, It's preventing my program from being able to edit it's own settings. I am using Microsoft's recommended approach for storing application settings so there must be a way to allow the program to save it's own data. I know I could run the program as admin or even use compatibility mode to run as admin but that just seems jenky! The last time I installed iTunes and changed the program configuration, I didn't have to run as admin so I really shouldn't have to do the same when I'm using Microsoft's own technology to build a program. How can I solve this problem? I am simply trying to allow my application.exe file to write to the application.exe.config file. It really seems like this should be doable without admin rights or turning off UAC. Thanks

    Private Sub WriteApplicationSetting(strSetting As String, strvalue As String)
            Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            Dim applicationSectionGroup As ConfigurationSectionGroup = config.GetSectionGroup("applicationSettings")
    
            Dim strAppName As String = System.Reflection.Assembly.GetExecutingAssembly.GetName().Name
            Dim applicationConfigSection As ConfigurationSection = applicationSectionGroup.Sections(strAppName & ".My.MySettings")
            Dim clientSection As ClientSettingsSection = CType(applicationConfigSection, ClientSettingsSection)
    
            ' set a value to that specific property
            Dim applicationSetting As SettingElement = clientSection.Settings.Get(strSetting)
            applicationSetting.Value.ValueXml.InnerText = strvalue
    
            ' without this, saving won't work
            applicationConfigSection.SectionInformation.ForceSave = True
            ' save
            config.Save()
        End Sub
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.