1

ユーザー入力を取得してファイルに保存する小さなプログラムを作成しようとしていますが、そのファイルの要素数を 100 に制限したいと考えています。

ユーザーが 100 個の名前を追加し、ユーザーが追加する次の名前で「リストがいっぱいです」というメッセージが表示されるとします。

これまでに行ったコードは次のとおりです。

    public Form1()
    {
        InitializeComponent();
    }
    private string SongName, ArtistName;

    public void Registry()
    {
        List<Name> MusicList = new List<Name>(); //Create a List
        MusicList.Add(new Name(SongName = txtSongName.Text, ArtistName = txtArtistName.Text)); //Add new elements to the NameClass

        //check if the input is correct
        if (txtSongName.TextLength < 1 || txtArtistName.TextLength < 1)
        {
            Info info = new Info();
            info.Show();
        }
        else //if input is correct data will be stored
        { 
            //Create a file to store data
            StreamWriter FileSaving = new StreamWriter("MusicList", true);
            for (int i = 0; i < MusicList.Count; i++)
            {
                string sName = MusicList[i].songName; //Create new variable to hold the name
                string aName = MusicList[i].artistName; //Create new variable to hold the name
                FileSaving.Write(sName + " by "); //Add SongName to the save file
                FileSaving.WriteLine(aName); //Add ArtistName to the save file

            }
            FileSaving.Close();
        }
    }

    private void btnEnter_Click(object sender, EventArgs e)
    {
        Registry();
        //Set the textbox to empty so the user can enter new data
        txtArtistName.Text = "";
        txtSongName.Text = "";
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
4

2 に答える 2

3
 private const int MAX_STORED_SONGS = 100;//as class level field


 for (int i = 0; i < MusicList.Count && i < MAX_STORED_SONGS; i++)

 //...after the loop
 if( MusicList.Count > MAX_STORED_SONGS )
    errorMessageLabel.Text = "List is full, only 100 items added"

リストピッカーがどのように見えるかはわかりませんが、ページが送信される前にいくつかのjavascript /検証クライアント側を使用して、実際に100を超えるアイテムを選択できないようにすることをお勧めします.

あなたのコードについて明確ではないのは、ユーザーが 1 つの曲を送信したように見える間に、新しい空の MusicList を作成し、それに 1 つのアイテムを追加するが、複数のアイテムがあるかのようにループすることです。おそらく、最初にファイルを読み取ってその中に含まれる曲数を判断することから始めてください。そうすれば、いつ 100 曲になったかを判断できます。

于 2013-03-20T20:53:20.313 に答える
1

xml を使用して、データに何らかの構造を与えることをお勧めします。

現在の形式を維持したい場合は、ファイル内の NewLines をカウントし、そのカウントに加えて音楽リスト内の新しいアイテムが制限を超えるかどうかを確認するしかありません。

List<string> lines = new List<string>(System.IO.File.ReadAllLines(MyFile));
lines.Add(sName + " by " + aName);

int lineCount = lines.Count;
//limit reached
if(lineCount > 100 )
{
    //TODO: overlimit code
} else {
    System.IO.File.WriteAllLines(MyFile, lines.ToArray());
}
于 2013-03-20T20:56:36.217 に答える