public static string ResolveFromFile(string fileName) { ConnectionStringReference cnRef = null; using (StreamReader reader = File.OpenText(fileName)) { XmlSerializer xs = new XmlSerializer(typeof(ConnectionStringReference)); cnRef = (ConnectionStringReference)xs.Deserialize(reader); } if (!File.Exists(cnRef.Filename)) { return(null); } XmlDocument doc = new XmlDocument(); doc.Load(cnRef.Filename); string result = doc.SelectSingleNode(cnRef.XPath).InnerText; if (cnRef.Encryption.HasValue) { result = DecryptString(result, cnRef.Encryption.Value); } return(result); }
/// <summary> /// Creates a ConnectionStringReference for a given connection string with optional encryption. /// </summary> /// <param name="name">Name of XML file (without path) that will be created in ~/App Data/Local/Connection String Ref</param> /// <param name="connectionString">Connection string to reference, will be stored in ~/My Documents/Connection Strings/{Name}.xml</param> /// <param name="encryption">Data protection scope of connection string</param> public static string Create(string name, string connectionString, DataProtectionScope?encryption = null) { string refFile = GetFilename(name); if (File.Exists(refFile)) { throw new Exception($"Can't overwrite existing Connection String Reference file {refFile}"); } string settingsFile = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Connection Strings", name + ".xml"); string folder = Path.GetDirectoryName(settingsFile); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var cnSettings = new ConnectionStringSettingsFile() { ConnectionString = (encryption.HasValue) ? EncryptString(connectionString, encryption.Value) : connectionString, }; using (StreamWriter writer = File.CreateText(settingsFile)) { XmlSerializer xs = new XmlSerializer(typeof(ConnectionStringSettingsFile)); xs.Serialize(writer, cnSettings); } ConnectionStringReference cnRef = new ConnectionStringReference() { Name = name, Filename = settingsFile, XPath = "/Settings/ConnectionString" }; if (encryption.HasValue) { cnRef.Encryption = encryption.Value; } cnRef.Save(); return(settingsFile); }