Tim on September 28th, 2007

If you’re like me you’ve got thousands of songs in your iTunes library. I got a new notebook PC a couple months back, and I decided to move all my music to it since it’s got plenty of disk space. I know I had lots of songs in my library whose files didn’t exist anymore. There’s a script for removing dead tracks included with the iTunes COM download, so I figured I would port it over to a C# project.

The code is pretty straightforward. Get a reference to iTunes, check the file location of each track in the library and delete the tracks whose files don’t exist.
  

//create a reference to iTunes

iTunesAppClass iTunes = new iTunesAppClass();

//get a reference to the collection of all tracks

IITTrackCollection tracks = iTunes.LibraryPlaylist.Tracks;

for (int i = trackCount; i > 0; i–)

{

      IITTrack track = tracks[i];

      if (track.Kind == ITTrackKind.ITTrackKindFile)

      {

            IITFileOrCDTrack fileTrack = (IITFileOrCDTrack)track;          

            //if the file doesn’t exist, we’ll delete it from iTunes           

           if (fileTrack.Location == String.Empty || !System.IO.File.Exists(fileTrack.Location))            

          {

                  fileTrack.Delete();

            }

      }

}

You can download the project here (Download Project). I put it into a WinForm, used a worker thread to take care of the iTunes work because it can take some time to check a 10K song library, and output the dead tracks removed to a list box.

itunescsharp.jpg

I think in part 2 I’ll add the ability to find duplicate songs and remove the copy with the lower bitrate. I know for sure that I’ve got quite a few of them. Any other ideas for what can be done with the iTunes SDK to clean up your music library or to just make life simpler?

Here’s what I used for this project:

  • Visual C# 2008 Express Edition
  • iTunes 7.4.2.4
  • iTunes COM for Windows SDK
  • FYI. I found about 175 dead tracks out of over 7300 in my library.

    2 Responses to “iTunes SDK and C# – Part 1”

    Trackbacks/Pingbacks

    1. Scott Hanselman - Removing Dead Tracks (Duplicates that don't exist) from iTunes using C#
    2. Removing Dead Tracks (Duplicates that don’t exist) from iTunes using C# | Tolly Blog

    Leave a Reply

    You will be able to edit your comment after submitting.