我有一个 .NET Windows 窗体应用程序来显示图像,它访问 ConfigurationManager.AppSettings
以获取一些设置。
它在调试时工作正常,而且当我直接单击我编译的 exe 时,我可以从 app.config
文件中获取我的设置。
当我的应用程序不是由我直接执行时,问题就来了。当我将文件扩展名与其相关联,或手动执行“打开方式”时,我在访问ConfigurationManager.AppSettings
时得到空值。
有什么想法吗?
非常感谢
****编辑*****
我发现使用以下代码时会出现问题:
http://mel-green.com/2009/04/c-set-file-type-association/
基本上是文件关联。我不明白根本原因是什么,但是在资源管理器上手动执行文件关联问题不会发生。
谢谢
最佳答案
我试过这个并且它有效
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";
}
}
}
关于c# - ConfigurationManager.AppSettings - 打开时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26688906/