Search code examples
c#application-settings

Check if user.config is not exist


My application use application settings to store user's settings, the settings file name is user.config which stored in folder Application Data. In the first run of application, the file does not exist. I want to check if the user runs my application in the first time by the way I based on this file's existence. How to do it. Thanks.


Solution

  • Several ways.. one will be to check if some key value is empty:

    string sValue = ReadSetting("myKey");
    if (string.IsNullOrEmpty(sValue))
    {
       //file doesn't exist, handle...
    }
    

    And another way simple check using System.IO.File:

    if (!File.Exists("user.config"))
    {
       //file doesn't exist, handle...
    }
    

    Edit: to play safe with File.Exists have such code to generate the file full path:

    string strConfigPath = Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "user.config");
    if (!File.Exists(strConfigPath))
       ...
    

    This code is using System.Diagnostics namespace and will "map" the config file to the same folder as the active process.