-4

次のコードでは、文字列変数を取り込むようにストリームを変更するにはどうすればよいですか?

        // open dictionary file
        FileStream fs = new FileStream(dictionaryPath, FileMode.Open, FileAccess.Read, FileShare.Read);
        StreamReader sr = new StreamReader(fs, Encoding.UTF8);

        // read line by line
        while (sr.Peek() >= 0) 
        {
            string tempLine = sr.ReadLine().Trim();
            if (tempLine.Length > 0)
            {
                // check for section flag
                switch (tempLine)
                {
                    case "[Copyright]" :
                    case "[Try]" : 
                    case "[Replace]" : 
                    case "[Prefix]" :

                    ...
                    ...
                    ...
4

4 に答える 4

1

呼び出すだけでよいようです。ReadLine()この場合、のタイプをsrに変更できますTextReader

StreamReader次に、 yourをStringReaderに置き換えて、使用する文字列を渡すことができます。

TextReader sr = new StringReader(inputString);
于 2013-03-07T19:02:09.453 に答える
1

私の提案..「できれば、ストリームに近づかないでください」

この場合、次のことができます。

1) 文字列変数ですべてのファイルを読み取ります。

2) 行末文字 ( \r\n)で文字列の配列に分割します。

3)単純なforeachサイクルを実行し、switchステートメントをその中に入れます

ちょっとした例:

string dictionaryPath = @"C:\MyFile.ext";

string dictionaryContent = string.empty;

try // intercept file not exists, protected, etc..
{
    dictionaryContent = File.ReadAllText(dictionaryPath);
}
catch (Exception exc)
{
    // write error in log, or prompt it to user
    return; // exit from method
}

string[] dictionary = dictionaryContent.Split(new[] { "\r\n" }, StringSplitOptions.None);

foreach (string entry in dictionary)
{
    switch (entry)
    {
        case "[Copyright]":
            break;

        case "[Try]":
            break;

        default:
            break;
    }
}

この助けを願っています!

于 2013-03-07T20:22:13.290 に答える
0

StringReader のことですか?文字列の内容を読み取るストリームを作成します。

于 2013-03-07T19:02:09.780 に答える
0

文字列があり、それをストリームのように読み取りたい場合:

byte[] byteArray = Encoding.ASCII.GetBytes(theString);
MemoryStream stream = new MemoryStream(byteArray);
于 2013-03-07T19:11:53.410 に答える