This is a follow up to this SO post where I successfully implemented an AES encryption on an AML from a WinForms app to decrypting it from a Windows Service. This was ONLY IF a file like c:\test.xml was available to both programs. Otherwise, I got this dreaded Exception from the Windows Service:
Unable to load configuration data. Access to the path 'C:\worl\Project Alpha\Code\AlphaConfigurationUtility\AlphaConfigurationUtility\bin\Debug\alphaService.xml' is denied.
Obviously the hardcoding wouldn't work in Production but today, I took both the WinForm and Windows Service projects and had them write and read from the same directory. Now I am getting the same dreaded exception again.
EDIT: Could there be some permission issue for the Windows Service? It is running with an Admin account
What in this code potentially causing the file to be locked for access from the other program, the Windows Service program?
try
{
string fileName = System.IO.Path.Combine(Application.StartupPath, "alphaService.xml");
// var fileName = @"c:/text.xml";
XDocument doc = new XDocument();
XElement xml = new XElement("Info",
new XElement("DatabaseServerName", txtServerName.Text),
new XElement("DatabaseUserName", txtDatabaseUserName.Text),
new XElement("DatabasePassword", txtDatabasePassword.Text),
new XElement("ServiceAccount", txtAccount.Text),
new XElement("ServicePassword", txtServicePassword.Text),
new XElement("RegistrationCode", txtRegistrationCode.Text));
doc.Add(xml);
//using (var aes = Aes.Create())
//{
// aesKey = aes.Key;
// key = Convert.ToBase64String(aes.Key);
//}
string sKey = "LvtZELDrB394hbSOi3SurLWAvC8adNpZiJmQDJHdfJU=";
var aesKey = Convert.FromBase64String(sKey);
string encyptedText = EncryptDecrpt.EncryptStringToBase64String(doc.ToString(), aesKey);
File.WriteAllText(fileName, encyptedText);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
The decrypting program, the Windows service starts with and gets the exception on the File.ReadAllText:
string path = AppDomain.CurrentDomain.BaseDirectory;
eventLog1.WriteEntry(path);
string fileName = System.IO.Path.Combine(path, "alphaService.xml");
// var fileName = @"c:/text.xml";
string sKey = "LvtZELDrB394hbSOi3SurLWAvC8adNpZiJmQDJHdfJU=";
Byte[] keyBytes = Convert.FromBase64String(sKey);
var encryptedText = File.ReadAllText(fileName, new ASCIIEncoding());