ConfigurationManager.AppSettings - 在打开时返回null

时间:2014-11-01 11:35:44

标签: c# .net winforms

我有一个用于显示图像的.NET Windows窗体应用程序,可以访问ConfigurationManager.AppSettings以获取一些设置。

它在调试时工作正常,当我直接单击我编译的exe时,我可以从app.config文件中获取我的设置。

当我的申请未由我直接执行时,问题就出现了。当我将文件扩展名与其关联,或手动执行“打开方式”时,我将无效访问ConfigurationManager.AppSettings

有什么想法吗?

非常感谢

**** ***** EDIT

我发现当我使用以下代码时会出现问题:

http://mel-green.com/2009/04/c-set-file-type-association/

这基本上是文件关联。我不明白什么是根本原因,但是在资源管理器上手动执行文件关联不会发生这个问题。

由于

1 个答案:

答案 0 :(得分:0)

我试过这个及其工作

App.Config

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="ExtensionSupported" value ="jpeg,jpg"/>
  </appSettings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

<强> Program.cs的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if(args.Length>0)
                Application.Run(new Form1(args[0]));
            else
            Application.Run(new Form1());
        }
    }
}

<强> Form1.cs的

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private string p;

        public Form1()
        {
            InitializeComponent();



        }

        public Form1(string filePath):this()
        {
            MessageBox.Show("Loading file "+ filePath);
            CheckForAllowed(filePath);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = false;
            DialogResult dr=  openFileDialog1.ShowDialog();

            if (dr == System.Windows.Forms.DialogResult.OK)
                CheckForAllowed(openFileDialog1.FileName);

        }

        private void CheckForAllowed(string filePath)
        {
            string appSetting = ConfigurationManager.AppSettings["ExtensionSupported"];
            MessageBox.Show("Allowed file types are " + appSetting);
            string[] allowedFileTypes = appSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            string fileExtesnsion = filePath.Substring(filePath.LastIndexOf('.')+1).Trim();



            if (allowedFileTypes.Contains(fileExtesnsion))
                label1.Text = "Allowed";
            else
                label1.Text = "Not allowed";
        }

    }
}