📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

453行目: 453行目:
     }
     }
  }
  }
</syntaxhighlight>
<br>
==== YAMLファイルの修正 ====
以下の例では、YamlDotNetライブラリを使用して、指定されたYAMLファイルを非同期で修正している。<br>
<br>
YAMLファイルにおいて、修正する箇所を以下に示す。<br>
*
*
*
<br>
# ReadYamlFileAsyncメソッド
#: YAMLファイルを非同期で読み込む。
#: DeserializerBuilderを使用して、YAMLデータをDictionary<string, object>型にデシリアライズする。
#: CamelCaseNamingConventionを使用して、YAMLのキーをC#のプロパティ名に合わせている。
#: <br>
# ModifyCompanyDataメソッド
#: LINQのFirstOrDefaultメソッドを使用して、特定の従業員を検索する。
#: <br>
#: Alice Johnsonのskillに"Hardware Develop"を追加する。
#: Bob Williamsのpositionを"COO"に変更する。
#: 新しい従業員"Taro Yamada"を追加する。
#: <br>
# WriteYamlFileAsyncメソッド
#: 修正されたデータを再度YAMLフォーマットにシリアライズする。
#: File.WriteAllTextAsyncを使用して、YAML文字列をファイルに非同期で書き込む。
<br>
<syntaxhighlight lang="yaml">
# 変更前のYAMLファイル
company:
  name: Tech Solutions Inc.
  founded: 2010
  employees:
    - name: Alice Johnson
      position: CEO
      skills:
        - leadership
        - strategic planning
    - name: Bob Williams
      position: CTO
      skills:
        - programming
        - system architecture
  offices:
    headquarters:
      address: 123 Main St, Techville
      phone: 555-1234
    branch:
      address: 456 Innovation Ave, Codetown
      phone: 555-5678
</syntaxhighlight>
<br>
<syntaxhighlight lang="c#">
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
class Program
{
    static async Task Main(string[] args)
    {
      string filePath = "sample.yaml";  // 修正するYAMLファイルのパス
      try
      {
          // YAMLファイルを非同期で読み込む
          var companyData = await ReadYamlFileAsync(filePath);
          // データを修正
          ModifyCompanyData(companyData);
          // 修正したデータを非同期で書き込む
          await WriteYamlFileAsync(filePath, companyData);
      }
      catch (Exception ex)
      {
          Console.WriteLine($"エラーが発生: {ex.Message}");
      }
    }
    // YAMLファイルを非同期で読み込む
    static async Task<Dictionary<string, object>> ReadYamlFileAsync(string filePath)
    {
      var deserializer = new DeserializerBuilder()
                              .WithNamingConvention(CamelCaseNamingConvention.Instance)
                              .Build();
      using (var reader = new StreamReader(filePath))
      {
          var yaml = await reader.ReadToEndAsync();
          return deserializer.Deserialize<Dictionary<string, object>>(yaml);
      }
    }
    // 会社データを修正
    static void ModifyCompanyData(Dictionary<string, object> data)
    {
      var company = (Dictionary<string, object>)data["company"];
      var employees = (List<object>)company["employees"];
      // Alice Johnsonのskillに"Hardware Develop"を追加
      var alice = employees.FirstOrDefault(e => ((Dictionary<string, object>)e)["name"].ToString() == "Alice Johnson") as Dictionary<string, object>;
      if (alice != null)
      {
          var skills = (List<object>)alice["skills"];
          skills.Add("Hardware Develop");
      }
      // Bob Williamsのpositionを"COO"に変更
      var bob = employees.FirstOrDefault(e => ((Dictionary<string, object>)e)["name"].ToString() == "Bob Williams") as Dictionary<string, object>;
      if (bob != null)
      {
          bob["position"] = "COO";
      }
      // 新しい従業員"Taro Yamada"を追加
      var taro = new Dictionary<string, object>
      {
          ["name"] = "Taro Yamada",
          ["position"] = "CTO",
          ["skills"] = new List<string> { "monitoring", "programming" }
      };
      employees.Add(taro);
    }
    // YAMLファイルを非同期で書き込む
    static async Task WriteYamlFileAsync(string filePath, Dictionary<string, object> data)
    {
      var serializer = new SerializerBuilder()
                            .WithNamingConvention(CamelCaseNamingConvention.Instance)
                            .Build();
      var yaml = serializer.Serialize(data);
      await File.WriteAllTextAsync(filePath, yaml);
    }
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="yaml">
# 変更後のYAMLファイル
company:
  name: Tech Solutions Inc.
  founded: 2010
  employees:
    - name: Alice Johnson
      position: CEO
      skills:
        - leadership
        - strategic planning
        - Hardware Develop
    - name: Bob Williams
      position: COO
      skills:
        - programming
        - system architecture
    - name: Taro Yamada
      position: CTO
      skills:
        - monitoring
        - programming
  offices:
    headquarters:
      address: 123 Main St, Techville
      phone: 555-1234
    branch:
      address: 456 Innovation Ave, Codetown
      phone: 555-5678
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>