读取INI文件C#的特定部分 [英] Read specific part of an INI file C#

查看:138
本文介绍了读取INI文件C#的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有关读取ini文件的问题, 我需要使用im读取ini文件的特定部分,但无法弄清楚该如何做, 我已经可以读写ini文件了,但是我需要阅读特定的部分.

I have an question about reading an ini file, I need to read an specific part of the ini file im using and cannot figure out how to do this, I can already read and write from and to the ini file but i need to read an specific part.

这是我的INI文件:

[Settings]

[ACR]
11: Start Removal =90 // ms
12: Removal Time  =20 // commentary
13: Removal Delay =2.1 // commentary

[Cleaning]
21: Dur. Cleaning =90 //commentary
22: Time valve on =30  //commentary
23: Time valve off =15    //commentary

[Calibrate]
31: Content left =100//commentary
32: Calibrate left =--.-//commentary
33: Content right =100//commentary
34: Calibrate right =25.6//commentary

[Conductivity]
41: Factor left =500//commentary
42: Offset left =220//commentary
43: Factor right =500//commentary
44: Offset right =40//commentary
45: Level left =85//commentary
46: Level right =85//commentary

[General]
51: Type of valve =5//commentary
52: Indicator =2//commentary
53: Inverse output =0//commentary
54: Restart time =30//commentary
55: Water time =0//commentary
56: Gate delay =10//commentary

[Pulsation]
61: Pulsation p/m =60//commentary
62: S/r ratio front =55//commentary
63: S/r ratio back =60//commentary
64: Stimulation p/m =200//commentary
65: S/r stim front =30//commentary
66: S/r stim back =30//commentary
67: Stimulation dur =20//commentary

我必须读取该行的前2个字符,因此在ACR部分下,我需要读取10,11和12.在清理该部分时,我必须读取21,22,23,依此类推.

I have to read the first 2 characters of the line, so lets so under the section ACR i need to read 10,11 and 12. and with the section cleaning i have to read 21,22,23 and so on.

到目前为止,这是我的代码:

This is my code so far:

using System;
using System.Windows.Forms;
using Idento.Common.Utilities;
using Milk_Units;

namespace Milk_Units
{
    public class SettingsIniFile
    {
        private const String FileNameCustom = "Data\\Custom.ini";//Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), );
        private const String FileNameDefault = "Data\\Default.ini";//Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), );


        public Settings LoadSettings(bool defaults = false)
        {
            String fileName = defaults ? FileNameDefault : FileNameCustom;
            StringList input = new StringList().FromFile(fileName);

            //Settings settings = null;
            Settings settings = new Settings();

            foreach (var item in input)
            {
                String line = item.Trim();

                if (line.StartsWith("[") && line.EndsWith("]"))
                    continue;

                int index = line.IndexOf('=');
                if (index < 0)
                    continue;

                String key = line.Substring(0, index).Trim();

                String value = line.Substring(index + 1).Trim();
                String comment = "";
                index = value.IndexOf("//");
                if (index > -1)
                {
                    comment = value.Substring(index).Trim();
                    value = value.Substring(0, index).Trim();
                }

                // ACR
                if (Utils.EqualsIgnoreCase(key, "10: Start Removal"))
                    settings.AcrStartRemoval = value;
                else if (Utils.EqualsIgnoreCase(key, "11: Removal Time"))
                    settings.AcrRemovalTime = value;
                else if (Utils.EqualsIgnoreCase(key, "12: Removal Delay"))
                    settings.AcrRemovalDelay = value;
                // CLEANING
                else if (Utils.EqualsIgnoreCase(key, "21: Dur. Cleaning"))
                    settings.CleanDurCleaning = value;
                else if (Utils.EqualsIgnoreCase(key, "22: Time valve on"))
                    settings.CleanTimeValveOn = value;
                else if (Utils.EqualsIgnoreCase(key, "23: Time valve off"))
                    settings.CleanTimeValveOff = value;
                //CALIBRATE
                else if (Utils.EqualsIgnoreCase(key, "31: Content left"))
                    settings.CalibrateContentLeft = value;
                else if (Utils.EqualsIgnoreCase(key, "32: Calibrate left"))
                    settings.CalibrateCalibrateLeft = value;
                else if (Utils.EqualsIgnoreCase(key, "33: Content right"))
                    settings.CalibrateContentRight = value;
                else if (Utils.EqualsIgnoreCase(key, "34: Calibrate right"))
                    settings.CalibrateCalibrateRight = value;
                //CONDUCTIVITY
                else if (Utils.EqualsIgnoreCase(key, "41: Factor left"))
                    settings.ConductFactorLeft = value;
                else if (Utils.EqualsIgnoreCase(key, "42: Offset left"))
                    settings.ConductOffsetleft = value;
                else if (Utils.EqualsIgnoreCase(key, "43: Factor right"))
                    settings.ConductFactorRight = value;
                else if (Utils.EqualsIgnoreCase(key, "44: Offset right"))
                    settings.ConductOffsetRight = value;
                else if (Utils.EqualsIgnoreCase(key, "45: Level left"))
                    settings.ConductLevelLeft = value;
                else if (Utils.EqualsIgnoreCase(key, "46: Level right"))
                    settings.ConductLevelRight = value;
                //GENERAL
                else if (Utils.EqualsIgnoreCase(key, "51: Type of valve"))
                    settings.GeneralTypeOfValve = value;
                else if (Utils.EqualsIgnoreCase(key, "52: Indicator"))
                    settings.GeneralIndicator = value;
                else if (Utils.EqualsIgnoreCase(key, "53: Inverse output"))
                    settings.GeneralInverseOutput = value;
                else if (Utils.EqualsIgnoreCase(key, "54: Restart time"))
                    settings.GeneralRestartTime = value;
                else if (Utils.EqualsIgnoreCase(key, "55: Water time"))
                    settings.GeneralWaterTime = value;
                else if (Utils.EqualsIgnoreCase(key, "56: Gate delay"))
                    settings.GeneralGateDelay = value;
                //PULSATION
                else if (Utils.EqualsIgnoreCase(key, "61: Pulsation p/m"))
                    settings.PulsationPulsationPm = value;
                else if (Utils.EqualsIgnoreCase(key, "62: S/r ratio front"))
                    settings.PulsationSrRatioFront = value;
                else if (Utils.EqualsIgnoreCase(key, "63: S/r ratio back"))
                    settings.PulsationSrRatioBack = value;
                else if (Utils.EqualsIgnoreCase(key, "64: Stimulation p/m"))
                    settings.PulsationStimulationPm = value;
                else if (Utils.EqualsIgnoreCase(key, "65: S/r stim front"))
                    settings.PulsationSrStimFront = value;
                else if (Utils.EqualsIgnoreCase(key, "66: S/r stim back"))
                    settings.PulsationSrStimBack = value;
                else if (Utils.EqualsIgnoreCase(key, "67: Stimulation dur"))
                    settings.PulsationStimulationDur = value;



            }
            return settings;
        }

预先感谢,我知道即时通讯没有正确使用INI文件,但这是简便的方法.

Thanks in advance, and i know im using the INI file not properly but this is the easist way.

Awnser谢谢Neoistheone的帮助

      foreach (var item in input)
                    {
                        String line = item.Trim();

                        if (line.StartsWith("[") && line.EndsWith("]"))
                            continue;

                        int index = line.IndexOf('=');
                        if (index < 0)
                            continue;

                        String key = line.Substring(0, index).Trim();
                        String ID = line.Substring(0, line.IndexOf(':'));
                        String value = line.Substring(index + 1).Trim();
                        //String comment = "";
                        index = value.IndexOf("//");
                        if (index > -1)
                        {
                         ID = line.Substring(0, line.IndexOf(':'));
                            //comment = value.Substring(index).Trim();
                            value = value.Substring(0, index).Trim();
                        }



                        // ACR
                        if (Utils.EqualsIgnoreCase(key, "11: Start Removal"))
                           {
                           settings.AcrStartRemoval11 = value;
                           _settings.AcrId11.ID
                           }

返回设置; }

Return settings; }

推荐答案

这将为您做到:

var vals = File.ReadLines("C:\\TEMP\\test.ini")
    .SkipWhile(line => !line.StartsWith("[ACR]"))
    .Skip(1)
    .TakeWhile(line => !string.IsNullOrEmpty(line))
    .Select(line => new
    {
        Key = line.Substring(0, line.IndexOf(':')),
        Value = line.Substring(line.IndexOf(':') + 2)
    });

EXPLANATION

  • .SkipWhile(line => !line.StartsWith("[ACR]"))跳过直到找到所需的部分.
  • .Skip(1)跳过该行,因为我们确实要读取值.
  • .TakeWhile(line => !string.IsNullOrEmpty(line))读取直到找到空白行.
  • .Select(line => new...将每行的值选择为匿名类型.
  • .SkipWhile(line => !line.StartsWith("[ACR]")) skips until it finds the section it wants.
  • .Skip(1) skips that line because we really want to read values.
  • .TakeWhile(line => !string.IsNullOrEmpty(line)) reads until it finds a blank line.
  • .Select(line => new... selects the values of each line into an anonymous type.

因此,只要传递正确的部分,即可获得所需的任何部分.

So, just passing in the right section will get you whatever section you want.

这种方法的另一个好处是它的执行被推迟了,因此,如果您不必阅读整个文件来查找不会出现的部分.

The other benefit of this approach is that it's deferred execution so if you don't have to read the entire file to find the section it won't.

现在,在您的情况下,您可能需要稍微按摩一下以确保它不会读到行尾的注释,例如,通过更改最后一个Substring.这确实取决于实际的域需求,但这不会有太大的变化.

Now, in your case you may need to massage this a little to ensure that it doesn't read the comments at the end of the line for example by changing the last Substring. That really depends on the real domain needs but that won't be a big modification.

您当然也可以对其进行修改,以满足所需的任何其他类型的查询.

You can of course modify this as well to meet the needs of any other types of queries you need.

这篇关于读取INI文件C#的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆