[英]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.