C# 你调用的对象是空的。- App.config

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16131382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:06:16  来源:igfitidea点击:

Object reference not set to an instance of an object. - App.config

c#winformsms-access

提问by bucketblast

I receiving the error and in the local window I am seeing for both conSettings and connectionString value of null. I am right to say ConfigurationManager is null and I need to create a new object. Maybe I am using Access and perhaps I have missed something in App.config file. Can someone help me on how to solve this problem, please. Thanks in advance.

我收到错误并在本地窗口中看到 conSettings 和 connectionString 值为 null。我说 ConfigurationManager 为空是正确的,我需要创建一个新对象。也许我正在使用 Access,也许我错过了 App.config 文件中的某些内容。有人可以帮助我解决这个问题吗?提前致谢。

App.config file...

应用程序配置文件...

   <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <appSettings>
       <add key="MyDBConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data 
                   Source=E:\...\Database1.mdb"/>
    </appSettings>
    </configuration>

Form.cs file...

Form.cs 文件...

 private void btnShow_Click(object sender, EventArgs e)
    {
        ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];

        string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here

        try
        {
            con = new OleDbConnection(connectionString);
            con.Open();
            cmd = new OleDbCommand("SELECT * FROM Table1", con);
            objReader = cmd.ExecuteReader();
            while (objReader.Read())
            {
                txtID.Text = ds.Tables[0].Rows[rno][0].ToString();
                CBAgeGroup.Text = ds.Tables[0].Rows[rno][1].ToString();
                CBGender.Text = ds.Tables[0].Rows[rno][2].ToString();
                CBCrimOffen.Text = ds.Tables[0].Rows[rno][3].ToString();
                if (ds.Tables[0].Rows[rno][4] != System.DBNull.Value)
                {
                    photo_aray = (byte[])ds.Tables[0].Rows[rno][4];
                    MemoryStream ms = new MemoryStream(photo_aray);
                   pictureBox1.Image = Image.FromStream(ms);
                }
                txtCV.Text = ds.Tables[0].Rows[rno][5].ToString();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }

I have been advised to use App.config.

有人建议我使用 App.config。

VS 2010 C# MS Access 2003

VS 2010 C# MS Access 2003

UPDATE 1My App.config now looks like this...

更新 1我的 App.config 现在看起来像这样......

<configuration>
    <ConnectionString>
        <add key="MyDBConnectionString"   value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Raj\Education\C_Sharp\Test1\Database1.mdb"/>
    </ConnectionString>

I am now receiving error of..."Configuration system failed to initialize". I am looking at it now on Google.

我现在收到错误...“配置系统初始化失败”。我现在在谷歌上看。

Update 2Tried...

更新 2尝试...

<configuration>
 <connectionStrings>
<add name="MyDBConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data   
        Source=E:\...\Database1.mdb"/>
  </connectionStrings>
 </configuration>

Receiving error of "Object reference not set to an instance of an object" Googling again

接收错误“对象引用未设置为对象的实例”再次谷歌搜索

Update 3

更新 3

<configuration>
<connectionStrings>
    <clear />
    <add name="MyDBConnectionString"
     providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Source=\Database1.mdb" />
</connectionStrings>

With the update 3 I am receiving error the same error. I have included the Add reference System. Configuration and I have referenced using System.Configuration;

使用更新 3 我收到错误相同的错误。我已经包括了添加参考系统。配置和我已经使用 System.Configuration 进行了引用;

Conclusion

结论

Perhaps it maybe there is a technical gitch between VS 2010 and Access 2003. I shall not use App.config this time round. I know there will be no problem with SQL Server. So I will leave it that. Thanks Damith and Clint for your time.

也许VS 2010 和Access 2003 之间存在技术问题。这次我不会使用App.config。我知道 SQL Server 不会有问题。所以我就不说了。感谢 Damith 和 Clint 抽出宝贵时间。

采纳答案by Damith

you need to read AppSettings key as below ,

您需要阅读以下 AppSettings 键,

string connectionString = 
      ConfigurationSettings.AppSettings["MyDBConnectionString"];

still you receive empty value, try below steps

您仍然收到空值,请尝试以下步骤

  1. Select the App.Config file in the solution explorer
  2. In the property window select Copy to Output Directory to Copy Always.
  3. Now Build the application and try again.
  1. 在解决方案资源管理器中选择 App.Config 文件
  2. 在属性窗口中,选择复制到输出目录以始终复制。
  3. 现在构建应用程序并重试。

to access like below you need to add connectionStrings section in app config

要访问如下所示,您需要在应用程序配置中添加 connectionStrings 部分

  string connectionString = 
      ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here

sample app config

示例应用配置

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="MyDBConnectionString" 
    connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data 
               Source=E:\...\Database1.mdb"/>
  </connectionStrings>
</configuration>
<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="MyDBConnectionString" 
    connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data 
               Source=E:\...\Database1.mdb"/>
  </connectionStrings>
</configuration>

回答by Clint

This:

这个:

string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

is your problem.

是你的问题。

You're accessing ConfigurationManager.ConnectionStringsto get to your configuration item, but in the App.Configfile you've put it under appSettingswhich is a different section of the config file than ConnectionStrings

您正在访问ConfigurationManager.ConnectionStrings您的配置项,但在App.Config您将其放置的文件中,该文件appSettings与配置文件的不同部分ConnectionStrings

You could either put your connection string in the relevant ConnectionStringssection of the app.config (accessible with ConfigurationManager.ConnectionStrings, or access it against the appSettingssection.

您可以将连接字符串放在ConnectionStringsapp.config的相关部分(可通过ConfigurationManager.ConnectionStrings访问,或针对该appSettings部分访问它。

See:

看:

http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx

http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx

For MSDN guidelines on storing connection strings.

有关存储连接字符串的 MSDN 指南。

回答by Hassan

Check if you have put the app.config file under your startup project or not. In my case, I just had to put the app.config file under my startup project, and problem was solved.

检查您是否已将 app.config 文件放在您的启动项目下。就我而言,我只需将 app.config 文件放在我的启动项目下,问题就解决了。

回答by Priyabrata biswal

I too faced the same problem even after multiple scrutinizing the app.config files and my code for error, but i didn't found any errors in my code. Eventually i found a silly mistake that my compiler had by default taken the application configuration file name as 'app1.config', and when i changed it to 'app.config' every thing just worked fine for me.

即使在多次检查 app.config 文件和我的错误代码后,我也面临同样的问题,但我没有在我的代码中发现任何错误。最终我发现了一个愚蠢的错误,我的编译器默认将应用程序配置文件名作为“app1.config”,当我将其更改为“app.config”时,一切对我来说都很好。

Hope it will help.

希望它会有所帮助。

回答by Randy Hall

This happened to me in class library with a console app set to run for debugging.

这发生在我的类库中,控制台应用程序设置为运行以进行调试。

It is necessary to add the connection to the app.config in the console app, as it will not find it in your library if you're starting it from an outside process.

有必要在控制台应用程序中添加到 app.config 的连接,因为如果您从外部进程启动它,它将不会在您的库中找到它。