13,002
回編集
437行目: | 437行目: | ||
==== INIファイルの書き込み ==== | ==== INIファイルの書き込み ==== | ||
以下の例では、INIファイルを非同期で書き込みするクラスを定義している。<br> | |||
<br> | |||
<syntaxhighlight lang="c#"> | |||
using System; | |||
using System.IO; | |||
using System.Threading.Tasks; | |||
using IniParser; | |||
using IniParser.Model; | |||
public class IniParserWriter | |||
{ | |||
private readonly FileIniDataParser _parser; | |||
private IniData _iniData; | |||
public IniParserWriter() | |||
{ | |||
_parser = new FileIniDataParser(); | |||
_iniData = new IniData(); | |||
} | |||
// INIファイルを非同期で書き込む | |||
public async Task WriteIniFileAsync(string filePath) | |||
{ | |||
try | |||
{ | |||
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) | |||
using (var streamWriter = new StreamWriter(fileStream)) | |||
{ | |||
var content = _parser.Parser.WriteToString(_iniData); | |||
await streamWriter.WriteAsync(content); | |||
} | |||
Console.WriteLine("INIファイルの書き込みが完了"); | |||
} | |||
catch (UnauthorizedAccessException) | |||
{ | |||
Console.WriteLine("ファイルへの書き込み権限がない"); | |||
} | |||
catch (IOException ex) | |||
{ | |||
Console.WriteLine($"ファイルの書き込み中にエラーが発生: {ex.Message}"); | |||
} | |||
catch (Exception ex) | |||
{ | |||
Console.WriteLine($"予期せぬエラーが発生: {ex.Message}"); | |||
} | |||
} | |||
// 値を設定する | |||
public void SetValue(string section, string key, string value) | |||
{ | |||
_iniData[section][key] = value; | |||
} | |||
// セクションを追加する | |||
public void AddSection(string section) | |||
{ | |||
if (!_iniData.Sections.ContainsSection(section)) | |||
{ | |||
_iniData.Sections.AddSection(section); | |||
} | |||
} | |||
// セクションを削除する | |||
public void RemoveSection(string section) | |||
{ | |||
_iniData.Sections.RemoveSection(section); | |||
} | |||
// キーを削除する | |||
public void RemoveKey(string section, string key) | |||
{ | |||
_iniData[section].RemoveKey(key); | |||
} | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
上記のクラスを使用する場合は、以下に示すようにインスタンスを生成して、メソッドを実行する。<br> | |||
<syntaxhighlight lang="c#"> | |||
var iniWriter = new IniParserWriter(); | |||
// セクションを追加する | |||
iniWriter.AddSection("新しいセクション"); | |||
// セクション, キー, 値をセット | |||
iniWriter.SetValue("新しいセクション", "新しいキー", "新しい値"); | |||
// INIファイルへ書き込む | |||
await iniWriter.WriteIniFileAsync("sample.ini"); | |||
</syntaxhighlight> | |||
<br><br> | <br><br> | ||