0

列と呼ばれる配列に入力しようとしているテキスト ファイルがあります。テキスト ファイルの各行は、作成したサブクラスの異なる属性に属しています。

たとえば、テキスト ファイルの行 2 は、渡したい日付です...区切り記号がないため、分割を使用したくありませんが、代わりの方法がわかりません。誰かが助けてくれるなら、私は以下を完全には理解していません。実行しようとすると、columns[1] が範囲外と表示されます...ありがとうございます。

StreamReader textIn = 
    new StreamReader(
    new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

//create the list
List<Event> events = new List<Event>();

while (textIn.Peek() != -1)
{
    string row = textIn.ReadLine();
    string[] columns = row.Split(' ');
    Event special = new Event();
    special.Day = Convert.ToInt32(columns[0]);
    special.Time = Convert.ToDateTime(columns[1]);
    special.Price = Convert.ToDouble(columns[2]);
    special.StrEvent = columns[3];
    special.Description = columns[4];
    events.Add(special);
}

入力ファイルのサンプル:

1
20:00
25.00
ベートーベンの交響曲第9番
ルートヴィヒ ヴァン ベートーヴェンの 9 番目にして最後の傑作をお聴きください。
2
18:00
15.00
野球試合
チャンピオンシップ チームが宿敵と戦うのを見に来てください。
4

3 に答える 3

1

あなたの与えられたサンプルファイルのようなもの

string[] lines = File.ReadAllLines(path);

for (int index = 4; index < lines.Length; index += 5)
{
    Event special = new Event();
    special.Day = Convert.ToInt32(lines[index - 4]);
    special.Time = Convert.ToDateTime(lines[index - 3]);
    special.Price = Convert.ToDouble(lines[index - 2]);
    special.StrEvent = lines[index - 1];
    special.Description = lines[index];
    events.Add(special);
}

仕事はできますが、Tim が既に述べたように、ファイル形式の変更を検討する必要があります。

于 2013-04-22T05:58:22.853 に答える