Click here to Skip to main content
15,895,740 members
Articles / Programming Languages / C#

Use LINQ to Create Music Playlists

Rate me:
Please Sign up or sign in to vote.
3.25/5 (3 votes)
29 Aug 2008CPOL4 min read 30.8K   614   10  
See how to utilize LINQ along with Typed-DataSets to quickly build playlists for your music collection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace AllM3u
{
    class Program
    {
        const string WINDOWTITLE = "AllM3u Creater v0.1";
        const string A3EXT = ".m3u";
        const string MPEXT = ".mp3";
        const string ALLM3U = "!all" + A3EXT;

        static Guid _folderGuid;
        static Guid _fileGuid;

        static FolderData _ds;

        static void Main(string[] args)
        {
            Console.WriteLine("{0}", WINDOWTITLE);

            // Current folder name
            DirectoryInfo di = new DirectoryInfo(".");
            string workingFolder = di.FullName;

            // Put the dataset into memory
            _ds = new FolderData();

            // Collect files data
            Console.WriteLine("Collecting files information...");
            RecursePath(workingFolder);

            Console.WriteLine("Writing m3u files...");

            // Loop through folders
            foreach (var dr in _ds.dbFolders.Where(x => x.HasMp3s == true))
            {
                Console.Write(".");
                using (StreamWriter sr = new StreamWriter(Path.Combine(dr.Path, ALLM3U)))
                {
                    var resSet = from d in _ds.dbFolders
                                 join f in _ds.dbFiles on d.FolderId equals f.FolderId
                                 where d.Path.StartsWith(dr.Path) && d.HasMp3s == true
                                 select new { FullPath = Path.Combine(d.Path, f.Filename) };
                    foreach (var item in resSet)
                    {
                        sr.WriteLine(item.FullPath.Replace(dr.Path + @"\", ""));
                    }
                }
            }
            Console.WriteLine("Done!");
        }

        private static void RecursePath(string inPath)
        {
            DirectoryInfo folder = new DirectoryInfo(inPath);
            DirectoryInfo[] childFolders = folder.GetDirectories();
            FileInfo[] files = folder.GetFiles();

            bool hasMp3s = false;
            _folderGuid = Guid.NewGuid();

            FolderData.dbFoldersRow fdr = _ds.dbFolders.NewdbFoldersRow();
            fdr.FolderId = _folderGuid;
            fdr.Path = inPath;
            fdr.HasMp3s = hasMp3s;
            _ds.dbFolders.Rows.Add(fdr);

            foreach (var file in files)
            {
                // Does folder contain any mp3s?
                if (!hasMp3s && file.Extension.ToLower().Equals(MPEXT.ToLower()))
                {
                    hasMp3s = true;
                }

                // Remove any existing .m3u playlists
                if (file.Extension.ToLower().Equals(A3EXT.ToLower()))
                {
                    try
                    {
                        file.Delete();
                    }
                    catch (Exception Ex)
                    {
                        Console.WriteLine(string.Format("Can't delete file {0}:\r\n\t{1}", file.FullName, Ex.Message));
                    }
                }

                if (file.Extension.ToLower().Equals(MPEXT.ToLower()))
                {
                    _fileGuid = Guid.NewGuid();

                    FolderData.dbFilesRow rdr = _ds.dbFiles.NewdbFilesRow();
                    rdr.FileId = _fileGuid;
                    rdr.FolderId = _folderGuid;
                    rdr.Filename = file.Name;
                    _ds.dbFiles.Rows.Add(rdr);
                }
            }

            FolderData.dbFoldersRow dr = _ds.dbFolders.Single(x => x.FolderId == _folderGuid);
            dr.HasMp3s = hasMp3s;

            foreach (var item in childFolders)
            {
                RecursePath(Path.Combine(inPath, item.Name));
            }
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
Dave has been working in the software industry for a few years now. Having graduated with his BS in Computer Science & Engineering from the University of Toledo in 2002, Dave enjoys learning about new technologies and likes to apply new programming methods to solve age-old challenges. In his spare time he is addicted to movies (sci-fi, horror, anything good!) and spending time with family and friends. Dave also harbors a secret desire to make it big in the film/music industry—here’s lookin’ at you, kid! ;o)

Comments and Discussions