全部, 我希望在file.txt中保存我的音乐播放器播放的歌曲的年表。 我尝试了这段代码,但不起作用:
StreamWriter sw = new StreamWriter(@"c:\Media PlayList\List.txt");
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
wmp.URL = Convert.ToString(listBox1.SelectedItem);
foreach (object o in listBox1.SelectedItems)
{
sw.WriteLine(DateTime.Now + " - " + o.ToString());
}
}
我如何存储歌曲:
private List<string> GetFolder(string Folder)
{
string filena;
DirectoryInfo dir = new DirectoryInfo(Folder);
FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories);
List<string> str = new List<string>();
foreach (FileInfo file in files)
{
str.Add(file.FullName); }
}
private void Form2_Load(object sender, EventArgs e)
{
List<string> uno = GetFolder(@"D:\\Music\\");
listBox1.DataSource = uno;
listBox1.DisplayMember = "uno"; }
我需要每次音乐播放器更改歌曲时,文件“List.txt”将由listbox.SelectedItem更新,但我无法用我的代码更新“List.txt”。 哪里错了? 谢谢你的关注。
好的问候
编辑:我更新了我的代码段,希望它能够清楚。
答案 0 :(得分:1)
如果更新文件失败,您可能希望在构造函数中设置append参数,例如:
StreamWriter sw = new StreamWriter(@"c:\Media PlayList\List.txt", true);
如果它未能触发SelectedIndexChanged事件,请更新问题以反映...
答案 1 :(得分:1)
private void listBox1_SelectedIndexChanged(object sender,EventArgs e)
{
wmp.URL = Convert.ToString(listBox1.SelectedItem);
foreach (object o in listBox1.SelectedItems)
sw.WriteLine(DateTime.Now + " - " + o.ToString());
sw.close();
}
答案 2 :(得分:1)
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.DataSource = GetFolder("D:\\Music\\");
}
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mp3", SearchOption.AllDirectories))
FileList.Add(file.FullName);
return FileList;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter("c:\\Media PlayList\\List.txt", true);
wmp.URL = Convert.ToString(listBox1.SelectedItem);
foreach (object o in listBox1.SelectedItems)
sw.WriteLine(DateTime.Now + " - " + o);
sw.Close();
}
}
}
以上代码将为您完成工作。注意: