简体   繁体   English

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

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

I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. 我有一个列表框,显示使用dragDrop功能或OpenFileDialog打开的文件的名称,文件路径存储在名为播放列表的列表中,并且列表框仅显示名称,而不包含路径和扩展名。 When my form closes, the playlist content is saved to a .txt file. 当我的表单关闭时,播放列表内容将保存到.txt文件中。 When I open again my application, the content in the text file is stored again in the listbox and the playlist. 当我再次打开应用程序时,文本文件中的内容再次存储在列表框和播放列表中。 But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones. 但是当我重新打开表单后添加新文件时,我不知道为什么在最后一个文件和最近添加的文件之间留空白行。

This is the code I use to WRITE the content of playlist(List) in the txt file: 这是我用来在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();
        }

This is the code used to READ the same txt file: 这是用于读取同一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;
        }

    }

The code used to add files to listbox and playlist: 用于将文件添加到列表框和播放列表的代码:

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;

This is what I get when I add new files after re-opening my form: 这是在重新打开表单后添加新文件时得到的: !!!!

Thanks in advance, I hope StackOverflow community can help me! 在此先感谢您,希望StackOverflow社区能够为我提供帮助!

First of all: debug your code and you'll find the problem yourself :) 首先:调试您的代码,您会自己发现问题:)

Issue is the use of the WriteLine method. 问题是使用WriteLine方法。 The last line you write should use the Write method instead so that you don't have an empty line at the end. 您写的最后一行应改用Write方法,以便最后没有空行。 Alternatively and easier to implement is to only add non-empty lines to your playlist such like this: 另外一种更容易实现的方法是,仅将非空行添加到播放列表中,如下所示:

// ...
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);

As a side comment: while (true) and using exception handling is a bad approach to end a loop. 附带说明: while (true)并使用异常处理是结束循环的不好方法。

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

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