3

とてもシンプルなものだといいのですが。ウィンドウに表示したいテキストの記事があります。コードの中央にこの大量のテキストを配置するのではなく、リソースとして追加してウィンドウに読み上げることはできますか?

理由を尋ねる人にとって、それは単にそれが巨大な記事であり、私のコードの途中で立ち往生しているように見える非常に醜いからです。

HBの更新

私はこれに対していくつかの異なるアプローチを試しましたが、現在GetManifestResourceStream、embeddedResource(txtファイル)を調べて使用し、それを画面に書き込んでいます。まだテストを終了していませんが、機能する場合は、テキスト全体をコピーして貼り付けるよりもはるかに優れていますtxtbox1.Text = "...blah blah blah"

_textStreamReader = new    
StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Problem.Explaination.txt"));
                        try
                        {
                            if (_textStreamReader.Peek() != -1)
                            {
                                txtBlock.Text = _textStreamReader.ReadLine();
                            }
                        }
                        catch
                        {
                            MessageBox.Show("Error writing text!");
                        }

私の質問は残っています、これを達成するためのより良い方法はありますか(これが成功したと仮定して)ありがとう

ノート

上記の例では、1行のテキストのみが必要です。これをファイルから数行を読み取るように適合させる場合は、次のように変更します。

StreamReader _textStreamReader;
        _textStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Problem.Explaination.txt"));
        var fileContents = _textStreamReader.ReadToEnd();
        _textStreamReader.Close();

        String[] lines = fileContents.Split("\n"[0]);
        String[] lines2;
        Int16 count;
        foreach (string line in lines)
        {
        txtBlock.Text += line;
        }
4

2 に答える 2

1

ファイルをリソースとして追加し、コードで文字列に読み込みます。

    StringBuilder sb = new StringBuilder();
    using (var stream = this.GetType().Assembly.GetManifestResourceStream("MyNamespace.TextFile.txt"))
    using(var reader = new StreamReader(stream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
    }
    ViewModel.Text = sb.ToString();
于 2012-06-27T10:57:28.897 に答える
1

そのテキストをテキスト ファイルに配置し、コードで読み取ることができます。

http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx

于 2012-06-27T09:31:09.213 に答える