I am encountering a problem while reading config files. The scenario is like this, I have two programs. Program A reads its configuration from a config file and program B is only used to modify the contents of the config file which A reads. The name of the config file is email.config. It is in the same directory in which program A & B resides.

The problem is that I get path of a file for attachment using open file dialog in program B. If the path points to a file in the same directory, program B works perfect while saving the data back to the config file! But if it points to a file outside the directory it throws an exception of type System.NullReferenceException.

I have placed comments in the code where the exception occurs.

Here is the code

static readonly string configFileName = "email.config";

private void saveBtn_Click(object sender, EventArgs e)
		// save everything and close
		string serverAddr = serverAddressTxtBox.Text;
		string port = portTxtBox.Text;
		bool ssl = sslRadioYes.Checked == true ? true : false;
		string senderAddr = senderTxtBox.Text;
		string password = passwordTxtBox.Text.Length != 0 ? Encrypt(passwordTxtBox.Text) : "";
		string subject = subjectTxtBox.Text;
		string attachment = attachTxtBox.Text;
		string messageBody = msgBodyTxtBox.Text;
		var configMap = new ExeConfigurationFileMap { ExeConfigFilename = configFileName };
		Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
		/* If attachment points to a file outside the exes directory
		externalConfig doesn't reads the config properly
		and throws exception of type System.NullReferenceException */
		// here the exception is thrown
		externalConfig.AppSettings.Settings["ServerAddress"].Value = serverAddr;
		externalConfig.AppSettings.Settings["Port"].Value = port;
		externalConfig.AppSettings.Settings["SSL"].Value = ssl.ToString();
		externalConfig.AppSettings.Settings["Sender"].Value = senderAddr;
		externalConfig.AppSettings.Settings["SenderPassword"].Value = password;
		externalConfig.AppSettings.Settings["Subject"].Value = subject;
		externalConfig.AppSettings.Settings["AttachmentPath"].Value = attachment;
		externalConfig.AppSettings.Settings["Body"].Value = messageBody;

			// Save values in config
	catch (System.Exception ex)
		MessageBox.Show("Error: " + ex.Message);

Well, I configured it out myself after debugging for almost 5 hours, Damn!

The problem was when I used OpenFileDialog to get the file path, it changed the current directory to the one which is selected in the dialog, so the program couldn't find the config file. All I did was to set the RestoreDirectory property of OpenFileDialog to true and *poof* it worked

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.