简体   繁体   中英

Best method to store a large number of constants C#

Fairly new to c#, I have a datatable with 250 rows, one of the columns will be populated with constant values (these values are strings). What is the best way to store these constants? Any reference links to your suggestions would be greatly appreciated. One method I was thinking was using an xml file but I am unsure how easy it would then be to add values to the datatable.

Assuming that you want to store from a file to a database...

C# XML support is fine :

using System;
using System.Xml;

Then assuming you have this kind of XML structure :

<Db>
    <Item str_attr="ghjgjg" other_attr="0" .../>
    <Item str_attr="fsfsff" other_attr="1" .../>
    ...
</Db>

Then you can browse it as follows :

XmlTextReader textReader = new XmlTextReader("db.xml");
while (textReader.Read())
{
    String str = textReader.GetAttribute("str_attr");
    if (str != null) { // The current item has an attribute named "str_attr"
        // Code to insert 'str' to db here
   }
}

This is pretty straight forward.

Possible code to populate the database :

SqlCommand cmd = new SqlCommand(...);
cmd.CommandText = "INSERT INTO my_table (my_str_field) " + "VALUES (@str)";
cmd.Parameters.AddWithValue("@str", str);
cmd.ExecuteNonQuery();

So what I ended up doing is the following:

I Created an xml with the following format

<Db>
    <identify>
        <row>
            <column2>Name</column2>
            <column3></column3>
        </row>
          :
          :
          :
     </identify>
</Db>

Then to read the information from the xml file I used the following code:

XmlTextReader textReader = new XmlTextReader("db.xml");
textReader.ReadStartElement("Db");
string column2="";
for (int row = 0; row < NumOfRows; row++)
{
    if (row == 0)
    {
        textReader.ReadStartElement("identify");
    }

    textReader.ReadStartElement("row");
    column2 = textReader.ReadElementString("column2");
    dataView[row][2] = column2;
    dataView[row][3] = textReader.ReadElementString("column3");
    textReader.ReadEndElement(); //row
}

Note: I am using the information stored in the xml and placing it into a datatable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM