When you install Apple iTunes, it includes a COM automation library (see link for SDK docs).  It is very easy to use!  Thanks to Dan Crevier’s blog post for pointing me in the right direction to the SDK.

I needed to remove all the tracks in iTunes that no longer exist on my disk (I move my files around a lot).  The SDK included a JScript example that I converted to C# .NET (below).

Just create a new C# Console application, copy/paste this into Program.cs, and change the project properties from a Console application to a Windows Application, and look for the app’s output in the Output Window.  You’ll also need to add a project reference to the COM library “iTunes 1.7 Type Library”.

Here is the sample code: iTunesRemoveDeadFiles.zip

using System;

using iTunesLib;

 

namespace RemoveDeadFiles

{

   class Program

   {

      static void Main(string[] args)

      {

         // iTunes classes

         iTunesAppClass itunes = new iTunesAppClass();

         IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;

         IITTrackCollection tracks = mainLibrary.Tracks;

         IITFileOrCDTrack currTrack;

 

         // working variables

         int numTracks = tracks.Count;

         int deletedTracks = 0;

 

         while (numTracks != 0)

         {

            // only work with files

            currTrack = tracks[numTracks] as IITFileOrCDTrack;

 

            // is this a file track?

            if (currTrack != null && currTrack.Kind == ITTrackKind.ITTrackKindFile)

            {

               // yes, does it have an empty location?

               if (currTrack.Location == null)

               {

                  // yes, delete it

                  currTrack.Delete();

                  deletedTracks++;

               }

            }

 

            // progress to the next tack

            numTracks--;

         }

 

         // report to the user the results

         System.Diagnostics.Trace.WriteLine(

            String.Format("Removed {0} track{1}.", deletedTracks,

            deletedTracks == 1 ? "" : "s"));

      }

   }

}