Moving Windows Media Player Ratings into iTunes

I tried to do this a while ago, and ran into problems with iTunes crashing when I tried to set ratings. I tried this again with iTunes 4.9 and it worked! I don't know if it was my system that was at fault, or if it was an iTunes bug, but either way now I have an application that can read ratings from Windows Media Player 9 and write them into iTunes.

I do it by filename. All my music files are named {Artist} - {Album} - {Track} - {SongName} so I know they're all unique. If you do something different, such that the same filename might be used by more than one song, then you'll probably not want to use this program.

I wrote it in C#. Adding references to the iTunes Music Library COM object, and the Windows Media Player COM object gave me WMPLib and iTunesLib namespaces in my app.

using WMPLib;
using iTunesLib;

Reading from Windows Media Player is simple enough:

WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
IWMPMediaCollection mediaCollection = wmp.mediaCollection;
IWMPPlaylist allMedia = mediaCollection.getAll();

And then stepping through the playlist. Don't forget that COM enumeration start from 1, not 0, so the for loop should look like:

for (int i = 1; i <= allMedia.count; i++)

While I'm reading the ratings out of WMP, I'm building a dictionary of filenames to ratings. Then I step through all the songs in the iTunes database, doing a quick dictionary lookup to see if I have a rating for each song.

The only tricky thing about this is the cast to IITFileOrCDTrack:

IITFileOrCDTrack track = (IITFileOrCDTrack)iTunes.LibraryPlaylist.Tracks[i + 1];

This seems to be necessary because a track in a playlist is the base class IITTrack, which doesn't expose the location of the track. The cast will fail for some media types (like radio stations) so be ready to handle that.

I wrote my app using the .NET Framework 2.0 beta. You can download the binary here, but you'll need a .NET Framework 2.0 beta to run it. It's a simple command line app that, when run, will copy all the ratings from your Windows Media Player songs that have ratings, into any songs in iTunes that have the same filename and are not yet rated.