首页 文章

如何将List <string>中的内容保存到C#中的文本文件中?

提问于
浏览
0

我有一个列表框,显示使用dragDrop功能或OpenFileDialog打开的文件的名称,文件路径存储在List命名的播放列表中,列表框仅显示没有路径和扩展名的名称 . 当我的表单关闭时,播放列表内容将保存到.txt文件中 . 当我再次打开我的应用程序时,文本文件中的内容再次存储在列表框和播放列表中 . 但是当我重新打开表单后添加新文件时,我不知道为什么它会在最后一个文件和最近添加的文件之间留下空白 .

这是我用来在txt文件中写入播放列表(List)内容的代码:

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        if(listBox1.Items.Count > 0)
        {
            StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
            foreach (String s in playlist)
            {
                str.WriteLine(s);
            }
            str.Close();
        }

这是用于读取相同txt文件的代码:

private void Form1_Load(object sender, EventArgs e) //Form Load!!!
    {
        FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
        if(info.Exists)
        {
            if (info.Length > 0)
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
                try
                {
                    do
                    {
                        string currentRead = reader.ReadLine();
                        playlist.Add(currentRead);
                        listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));

                    } while (true);
                }
                catch (Exception)
                {
                    reader.Close();
                    listBox1.SelectedIndex = 0;
                }
            }
            else
            {
                File.Delete(Application.StartupPath + "/Text.txt");
            }
        }
        else
        {
            return;
        }

    }

用于将文件添加到列表框和播放列表的代码:

OpenFileDialog ofd = new OpenFileDialog();
        ofd.Title = "Select File(s)";
        ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
        ofd.InitialDirectory = "C:/";
        ofd.RestoreDirectory = false;
        ofd.Multiselect = true;
        ofd.ShowDialog();

        foreach (string s in ofd.FileNames)
        {
            listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
            playlist.Add(s);
        }


        listBox1.SelectedIndex = 0;

这是我在重新打开表单后添加新文件时得到的结果:
!!!!

在此先感谢,我希望StackOverflow社区可以帮助我!

1 回答

  • 0

    首先:调试你的代码,你会发现自己的问题:)

    问题是使用 WriteLine 方法 . 您编写的最后一行应使用 Write 方法,以便最后没有空行 . 另外,更容易实现的是只向播放列表中添加非空行,如下所示:

    // ...
    do
    {
        string currentRead = reader.ReadLine();
        if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
        {
            playlist.Add(currentRead);
           listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
        }
    } while (true);
    

    作为旁注: while (true) 并使用异常处理是一种结束循环的坏方法 .

相关问题