<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; AHK: Ini file object]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=14886&amp;type=atom" />
	<updated>2019-07-28T11:32:25Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=14886</id>
		<entry>
			<title type="html"><![CDATA[AHK: Ini file object]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=135091#p135091" />
			<content type="html"><![CDATA[<p>Создаёт массив из ини файла, и записывает этот массив обратно (перезапись файла целиком).<br />Зачем это может пригодится:<br /></p><ul><li><p>Файл сетевой, и каждое обращение к нему занимает время</p></li><li><p>Частое внесение настроек, и не хочется &quot;дёргать&quot; жёсткий диск</p></li><li><p>Требуется в какой-то момент решать - сохранять или не сохранять все новые настройки</p></li></ul><br /><h5>Методы:</h5><p><strong>New(File, FileBackUp = &quot;&quot;)</strong><br />File - путь к ини файлу.<br />FileBackUp - путь к файлу, если указан и были внесены новые настройки, при вызове Save в этот файл будут скопированы прежние настройки.</p><p><strong>Read(Section, Key, Default = &quot;&quot;)</strong><br />Section - секция.<br />Key - ключ.<br />Default - если ключа не существует, будет возвращено это значение, если не указано, то будет возвращено пустое значение.</p><p><strong>Write(Section, Key, Value = &quot;&quot;)</strong><br />Без комментариев.</p><p><strong>Delete(Section, Key)</strong><br />Без комментариев.</p><p><strong>DeleteSection(Section)</strong><br />Удаляет секцию.</p><p><strong>Save()</strong><br />Перезаписывает файл целиком если были внесены новые настройки, то есть если вызывались методы Write, Delete или DeleteSection.</p><br /><h5>Важно:</h5><p>Если хотите использовать уже существующий файл, надо преобразовать его в UTF-8 с BOM, иначе может испортить не ANSI символы. <br />Порядок секций и ключей в файле будет всегда в алфавитном порядке.<br />Комментарии не сохранятся.<br />Если файла не существует, метод Write не создаёт новый файл.</p><br /><h5><a href="http://forum.script-coding.com/viewtopic.php?pid=135127#p135127">Тема для обсуждения.</a></h5><br /><h5>Пример:</h5><div class="codebox"><pre><code>
Ini := new IniFile(A_ScriptDir &quot;\Settings.Ini&quot;)

MsgBox % Ini.Read(&quot;MySection1&quot;, &quot;MyKey1&quot;, &quot;Default&quot;)

Ini.Write(&quot;MySection1&quot;, &quot;MyKey1&quot;, A_TickCount)

Ini.Save()

ExitApp
</code></pre></div><br /><h5>Class:</h5><div class="codebox"><pre><code>
Class IniFile {
	__New(File, FileBackUp = &quot;&quot;) {
		this.Path := File
		this.FileBackUp := FileBackUp
		
		oFile := FileOpen(this.Path, &quot;r`n&quot;, &quot;UTF-8&quot;) 
		Str := oFile.Read()
		oFile.Close()  
		Pos := 1 
		While Pos := RegExMatch(&quot;`n&quot; Str, &quot;S)\n\s*\[(.*?)]\s*\n(.*?)(\n\s*\[.*?]\s*\n|$)&quot;, Match, Pos)
		{   
			Pos += StrLen(Match) - StrLen(Match3)
			this.Data[Section := Match1] := {}
			Loop, Parse, Match2, `n, `r
			{
				RegExMatch(A_LoopField, &quot;S)\s*(.*?)\s*=(.*)&quot;, V)
				If !StrLen(V1)
					Continue
				this.Data[Section, V1] := V2
			}
		}
	}
	Read(Section, Key, Default = &quot;&quot;) {
		If (Default != &quot;&quot; &amp;&amp; !this.Data[Section].HasKey(Key))
			Return Default
		Return this.Data[Section][Key]
	}
	Write(Section, Key, Value = &quot;&quot;) {
		If !IsObject(this.Data[Section])
			this.Data[Section] := {}
		this._CheckChanged()
		Return this.Data[Section][Key] := Value
	}
	Delete(Section, Key) {
		this._CheckChanged()
		Return this.Data[Section].Delete(Key)
	}
	DeleteSection(Section) {
		this._CheckChanged()
		Return this.Data.Delete(Section)
	}
	_CheckChanged() {
		If !this.changed
			this.changed := 1 
	}
	Save() {
		If !this.changed
			Return
		For Section, Keys in this.Data
		{ 
			Str .= &quot;[&quot; Section &quot;]`n&quot;
			For Key, Value in Keys
				Str .= Key &quot;=&quot; Value &quot;`n&quot;
		}
		If this.FileBackUp
			FileCopy, % this.Path, % this.FileBackUp, 1

		oFile := FileOpen(this.Path, &quot;w&quot;, &quot;UTF-8&quot;)
		oFile.Length := 0
		oFile.Write(Str)
		oFile.Close()
	}
}
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[serzh82saratov]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27879</uri>
			</author>
			<updated>2019-07-28T11:32:25Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=135091#p135091</id>
		</entry>
</feed>
