2009-04-27 84 views
1

HI全部, 我希望保存在我的音乐播放器播放的歌曲的时间顺序file.txt中。 我想这个代码片段,但不工作:将ListBox_SelectedItem保存到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”与我的代码。 我错在哪里? 感谢您的关注。

尼斯问候

编辑:我更新了我的代码片段,希望这将是明显的。

回答

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(); 
     } 
    } 
} 

上述代码将为您完成工作。备注:

  • 如果您想追加到该文件,您应该在创建StreamWriter时传递true作为第二个参数。
  • 将数据写入文件后,您应该明确关闭StreamWriter,否则文件将为空。
  • 关闭文件后,您不能再写入文件。如果你想要,你可以重新打开它。
+0

HI Jahedbozorgan, 这工作很好,事实上我错了,因为我关闭了文件,它总是空的,你的圆锥片段我解决了麻烦。 非常感谢。 – JayJay 2009-04-28 01:21:43

1

如果它未能更新文件,你可能要设置的附加参数的构造函数,例如:

StreamWriter sw = new StreamWriter(@"c:\Media PlayList\List.txt", true); 

如果它未能触发SelectedIndexChanged事件,请更新的问题,以反映那......

1

私人无效listBox1_SelectedIndexChanged(对象发件人,EventArgs的)

{ 
    wmp.URL = Convert.ToString(listBox1.SelectedItem); 

    foreach (object o in listBox1.SelectedItems) 
      sw.WriteLine(DateTime.Now + " - " + o.ToString());   
    sw.close(); 
}