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

标签 c#

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

关于C# 如何使存储文件的上限为 100 项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534472/

相关文章:

c# - 使用Html.TextBoxFor时如何设置文本框的宽度

c# - 主对象和嵌套对象中的Elastic Search 2.0搜索查询

c# - 通用类型转换

c# - 自适应用户界面/环境算法

c# - 无法确定导航属性 ASP.NET core 2.0 Entity Framework 表示的关系

c# - 是否可以通过反射调用 "Select"方法

c# - 根据今天的日期格式化通用列表中的日期(WPF、DataGrid、C#)

c# - 返回字节数组作为具有 Image/png 内容类型的 Http 响应

c# - Excel-C# : How to read the formulas from a cell?

c# - 使用 ITextsharp 将 Html 导出为 PDF