Playlist.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace MusicPlayer
  5. {
  6. public class Playlist
  7. {
  8. public string name { get; }
  9. private string basedir;
  10. public List<Song> songs;
  11. private APIHandler api;
  12. public Playlist(string name, string basedir, APIHandler api)
  13. {
  14. this.songs = new List<Song>();
  15. this.name = name;
  16. this.api = api;
  17. this.basedir = basedir;
  18. this.ReadFromFile();
  19. }
  20. public void AddSong(Song s)
  21. {
  22. this.songs.Add(s);
  23. }
  24. public List<Song> GetSongs()
  25. {
  26. return songs;
  27. }
  28. public void ReadFromFile()
  29. {
  30. try {
  31. using (StreamReader str = new StreamReader(basedir + name + ".txt"))
  32. {
  33. string readline;
  34. while ((readline = str.ReadLine()) != null)
  35. {
  36. string[] songsvalues = readline.Split('|');
  37. songs.Add(new Song(songsvalues[0], songsvalues[1], songsvalues[2], songsvalues[3], songsvalues[4], Int32.Parse(songsvalues[5]), api));
  38. }
  39. }
  40. }
  41. catch (FileNotFoundException)
  42. {
  43. FileStream fs = new FileStream(basedir + name + ".txt", FileMode.CreateNew);
  44. fs.Close();
  45. ReadFromFile();
  46. }
  47. }
  48. public void WriteToFile()
  49. {
  50. using (StreamWriter stw = new StreamWriter(basedir + name + ".txt"))
  51. {
  52. this.songs.ForEach(s =>
  53. {
  54. stw.WriteLine(s.ToString());
  55. });
  56. stw.Flush();
  57. }
  58. }
  59. }
  60. }