Skip to main content
 首页 » 编程设计

C# 如何使存储文件的上限为 100 项

2024年02月13日13飞鱼

我正在尝试制作一个小程序来获取用户输入并将其存储在一个文件中,但我希望该文件的元素上限为 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(); 
    } 

请您参考如下方法:

 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 个项目。

您的代码不清楚的是,当用户提交一首歌曲时,您创建了一个新的空 MusicList,向其中添加了一个项目,但是您循环遍历它,就好像有多个项目一样。也许您应该首先阅读文件以确定其中有多少首歌曲,这样您就可以确定它何时达到 100 首歌曲。