
This is a snippet used to populate a TreeView with your music library, based on the path provided.
Instructions: Provide a path to your music library
Pass the TreeView control you wish to populate
Add a reference to the System.IO Namespace
Call the method
//Namespace reference
using System.IO
/// <summary>
/// method to populate our TreeView with the files from
/// our music directory
/// </summary>
/// <param name="tv">TreeView control to populate</param>
public void PopulateMusicLibrary(string dir,TreeView tv)
{
//extensions we want to load
string[] extensions = { ".mp3", ".wma", ".mp4", ".wav" };
DirectoryInfo _rootDir = new DirectoryInfo(dir);
try
{
tv.BeginUpdate();
tv.Nodes.Clear();
//loop thorugh the directory provided gathering all the top level directories (artists)
foreach (DirectoryInfo artistDir in _rootDir.GetDirectories())
{
//create a tree node for each artist
TreeNode artistNode = new TreeNode(artistDir.FullName.Substring(artistDir.FullName.LastIndexOf(Path.DirectorySeparatorChar) + 1));
//loop thorugh each top level directory (artists) to get all it's subdirectories (albums)
foreach (DirectoryInfo albumDir in artistDir.GetDirectories())
{
//create a tree node for each album
TreeNode albumNode = new TreeNode(albumDir.Name.Replace("Parental Advisory", ""));
//loop through each subdirectory (albums) getting the files in each (songs)
foreach (FileInfo song in albumDir.GetFiles())
{
//loop through our extensions array
for (int i = 0; i < extensions.Length; i++)
{
//make sure the file has an extension we're looking for
if (song.Name.EndsWith(extensions[i]))
{
//add a new child node for each subdirectory (album)
albumNode.Nodes.Add(new TreeNode(song.Name.Replace("'", "\'")));
}
}
}
//add each subdirectory (album) to its corresponding top level directory (artists)
artistNode.Nodes.Add(albumNode);
}
//add the nodes to the TreeView
tv.Nodes.Add(artistNode);
}
tv.EndUpdate();
//collapse all the nodes
tv.CollapseAll();
}
//catch any exceptions that may have occurred
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Example usage
PopulateMusicLibrary("C:\\MyMusic",treeView1)-Offline- |