埋め込まれたリソーステキストファイルを読む方法 質問する

埋め込まれたリソーステキストファイルを読む方法 質問する

埋め込まれたリソース (テキスト ファイル) を読み取りStreamReader、それを文字列として返すにはどうすればよいですか? 現在のスクリプトでは、埋め込まれていないテキスト ファイル内のテキストをユーザーが検索して置換できるようにする Windows フォームとテキスト ボックスを使用しています。

private void button1_Click(object sender, EventArgs e)
{
    StringCollection strValuesToSearch = new StringCollection();
    strValuesToSearch.Add("Apple");
    string stringToReplace;
    stringToReplace = textBox1.Text;

    StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
    string FileContents;
    FileContents = FileReader.ReadToEnd();
    FileReader.Close();
    foreach (string s in strValuesToSearch)
    {
        if (FileContents.Contains(s))
            FileContents = FileContents.Replace(s, stringToReplace);
    }
    StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
    FileWriter.Write(FileContents);
    FileWriter.Close();
}

ベストアンサー1

あなたはAssembly.GetManifestResourceStream方法:

  1. 次の使用を追加します

     using System.IO;
     using System.Reflection;
    
  2. 関連ファイルのプロパティを設定する:値を持つ
    パラメータBuild ActionEmbedded Resource

  3. 次のコードを使用してください

     var assembly = Assembly.GetExecutingAssembly();
     var resourceName = "MyCompany.MyProduct.MyFile.txt";
    
     using (Stream stream = assembly.GetManifestResourceStream(resourceName))
     using (StreamReader reader = new StreamReader(stream))
     {
         string result = reader.ReadToEnd();
     }
    

    resourceNameは、 に埋め込まれたリソースの 1 つの名前ですassembly。たとえば、 という名前のテキスト ファイルを"MyFile.txt"、既定の名前空間 を持つプロジェクトのルートに埋め込むと"MyCompany.MyProduct"resourceNameになります"MyCompany.MyProduct.MyFile.txt"。アセンブリ内のすべてのリソースのリストを取得するには、Assembly.GetManifestResourceNames方法


resourceNameファイル名のみから取得する賢明な方法(名前空間の要素を省略) は次のとおりです。

string resourceName = assembly.GetManifestResourceNames()
  .Single(str => str.EndsWith("YourFileName.txt"));

完全な例:

public string ReadResource(string name)
{
    // Determine path
    var assembly = Assembly.GetExecutingAssembly();
    string resourcePath = name;
    // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
    if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
    {
        resourcePath = assembly.GetManifestResourceNames()
            .Single(str => str.EndsWith(name));
    }

    using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
    using (StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

または非同期拡張メソッドとして:

internal static class AssemblyExtensions
{
    public static async Task<string> ReadResourceAsync(this Assembly assembly, string name)
    {
        // Determine path
        string resourcePath = name;
        // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
        if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
        {
            resourcePath = assembly.GetManifestResourceNames()
                .Single(str => str.EndsWith(name));
        }

        using Stream stream = assembly.GetManifestResourceStream(resourcePath)!;
        using StreamReader reader = new(stream);
        return await reader.ReadToEndAsync();
    }
}

// Usage
string resourceText = await Assembly.GetExecutingAssembly().ReadResourceAsync("myResourceName");

おすすめ記事