Monday, June 14, 2010

My First F# App

I wanted to learn the basics of F# so i wrote a little app to organize my movie folder.  My movie folder was a folder that contained a bunch of movies.  I wanted to organize the movies alphabetically into folders with the first letter being the name of the folder.  After getting used to the syntax of F#, i found writing this little app to be just a easy as C#.
Here is the code:
Code Snippet
  1. #light
  2.  
  3. open System
  4. open System.IO
  5.  
  6. let title : string = "My Movie Organizer"
  7.  
  8. Console.WriteLine(title)
  9.  
  10. Console.WriteLine("This Application will move all files in a folder to subfolders with the first letter as the folder name.")
  11.  
  12. Console.WriteLine("Please enter the path of the folder you want to organize")
  13. let folderPath : string = Console.ReadLine()
  14.  
  15. if folderPath <> String.Empty then
  16.  
  17.     let dirInfo : DirectoryInfo = new DirectoryInfo(folderPath)
  18.  
  19.     for x : FileInfo in dirInfo.GetFiles() do
  20.         let firstLetter : char = x.Name.Chars 0
  21.     
  22.         let currentDirectory : DirectoryInfo = new DirectoryInfo(String.Format("{0}\\{1}\\", folderPath, firstLetter.ToString()))
  23.  
  24.         //If the current folder exists, move the file there else create the folder then move th file
  25.         if currentDirectory.Exists then
  26.             let xFilePath : string = currentDirectory.FullName
  27.             x.MoveTo(xFilePath + x.Name)
  28.         else
  29.             currentDirectory.Create()
  30.             let xFilePath : string = currentDirectory.FullName
  31.             x.MoveTo(xFilePath + x.Name)        
  32.         //Write out the file name and path    
  33.         Console.WriteLine(String.Format("Moving File {0} to Folder {1} ", x.FullName, currentDirectory.FullName))
  34. else
  35.     Console.WriteLine("Please specify a base path")
  36. //Wait for key press to end
  37. let endValue : string = Console.ReadLine()
Being a C# developer, i couldn’t help but explicitly type my variables (although unnecessary).  The first couple of lines are just writing out some text and waiting for the user to enter a path to a folder the want organized.  Next, the base folder path is opened as a directory info object.  Then we loop through all of the files in the directory and grab the first letter of the file name.  After checking if the folder exists, we either move the file or create the new folder and move the file.  The readline at the end just waits for the user to enter a key to end the program.
This is a very simple app and by no means enterprise level with error checking ,etc.  Just a basic app to move some files around in F#.

1 comment:

kodie said...

A dynamic language with access to the robust .NET library? Awesome!