winform客户端程序实时读写app.config文件

新接到需求,wcf客户端程序运行时,能实时修改程序的打印机名称;

使用XmlHelper读写 winform.exe.config文件修改后始终,不能实时读取出来,查询博客园,原来已有大神解释了;

获取电脑连接的打印机列表需要引入using System.Drawing.Printing;

       #region GetPrinters
        private List<string> GetPrinters()
        {
            var printerNames = new List<string>();
            foreach (var printer in PrinterSettings.InstalledPrinters)
            {
                printerNames.Add(printer.ToString());
            }
            return printerNames;
        }
        #endregion

 指定打印机列表默认显示打印机为配置文件中的打印机:

1     printerNames.ForEach(o =>
2            {
3                if (defaultPrinter == o)
4                    cbxPrinterList.SelectedIndex = printerNames.IndexOf(o);
5            });
View Code

确定按钮修改默认打印机名称

 1          #region 判断是否有key
 2             if (ConfigurationManager.AppSettings["DefaultPrinterName"] == null)
 3             {
 4                 XmlHelper.UpdateKey("DefaultPrinterName", "ZDesigner GT800-300dpi EPL", WMSWinConstant.ApplicatonName + ".exe");
 5             }
 6             else
 7             {
 8                 var printerName = cbxPrinterList.Text;
 9   
10                 //string appDomainConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
11                 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
12                 AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
13                 appSettings.Settings["DefaultPrinterName"].Value = printerName;
14                 config.Save();
15               //重点这句
16                 ConfigurationManager.RefreshSection("appSettings");
17             }
18             #endregion        
 获取默认打印机

public  static PrintDocument fPrintDocument = new PrintDocument();

//获取本机默认打印机名称 
public static String DefaultPrinter()
{
return fPrintDocument.PrinterSettings.PrinterName;
}

 

原文地址:https://www.cnblogs.com/yanghucheng/p/5742153.html