繁体   English   中英

如何从列表保存内容 <string> 到C#中的文本文件?

[英]How to save content from List<string> to a text file in C#?

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

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

 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社区能够为我提供帮助!

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

问题是使用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)并使用异常处理是结束循环的不好方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM