Как выбрать диапазон значений в операторе switch?

Предисловие

Во-первых, прочитайте это сообщение в блоге MSDN на ограничениях файлов INI . Если это соответствует вашим потребностям, читайте дальше.

Это краткая реализация, которую я написал, используя исходный Windows P / Invoke, поэтому он поддерживается всеми версиями Windows с установленной .NET (т.е. Windows 98 - Windows 10). Я передаю его в общественное достояние - вы можете свободно использовать его в коммерческих целях без атрибуции.

Маленький класс

Добавить новый класс с именем IniFile.cs в ваш проект:

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

// Change this to match your program's normal namespace
namespace MyProg
{
    class IniFile   // revision 11
    {
        string Path;
        string EXE = Assembly.GetExecutingAssembly().GetName().Name;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        public IniFile(string IniPath = null)
        {
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName.ToString();
        }

        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }
    }
}

Как использовать его

Откройте INI-файл одним из трех следующих способов:

// Creates or loads an INI file in the same directory as your executable
// named EXE.ini (where EXE is the name of your executable)
var MyIni = new IniFile();

// Or specify a specific name in the current dir
var MyIni = new IniFile("Settings.ini");

// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");

Вы можете написать несколько значений:

MyIni.Write("DefaultVolume", "100");
MyIni.Write("HomePage", "http://www.google.com");

Чтобы создать такой файл:

[MyProg]
DefaultVolume=100
HomePage=http://www.google.com

Чтобы прочитать значения из INI-файла:

var DefaultVolume = IniFile.Read("DefaultVolume");
var HomePage = IniFile.Read("HomePage");

По желанию вы может установить [Section]:

MyIni.Write("DefaultVolume", "100", "Audio");
MyIni.Write("HomePage", "http://www.google.com", "Web");

Чтобы создать такой файл:

[Audio]
DefaultVolume=100

[Web]
HomePage=http://www.google.com

Вы также можете проверить наличие такого ключа:

if(!MyIni.KeyExists("DefaultVolume", "Audio"))
{
    MyIni.Write("DefaultVolume", "100", "Audio");
}

Вы можете удалить такой ключ:

MyIni.DeleteKey("DefaultVolume", "Audio");

Вы также можете удалить целую секцию (включая все клавиши) следующим образом:

MyIni.DeleteSection("Web");

Пожалуйста, не стесняйтесь комментировать любые улучшения!

20
задан Rob Kennedy 24 February 2012 в 14:40
поделиться