Problem
I have image files that are RAW data and have the extension .NEF
Whatever edits I make to these files are stored in what is called a sidecar file with the extension .xmp
Given there are many photos and the photo numbering in the camera can only go up to 9999, there is a possibility that I may get duplicate filenames in the same folder over time.
Objective
Given the image files and the sidecar files must have the same base name to remain associated, I'd like to append the date the photo was taken to the base name for both files.
The original date can be found within the .xmp
file on a line beginning with a specific string.
I want to
- find all image files that have a sidecar file
- Get the image date from within the sidecar file
- Rename both the image file and sidecar file with the date appended at the end of the base name
Code
I'm pretty sure I'm not importing any namespace except System.IO
, so this should all be the .NET way, not any VB6.
Option Explicit On
Option Strict On
Option Infer On
Option Compare Text
Imports System.IO
Module PhotoRename
Sub Main()
Const DIR_PATH As String = "C:\Temp\"
Const IMAGE_EXTENSION As String = ".NEF"
Const SIDECAR_EXTENSION As String = ".xmp"
GetFilesInDirectory(DIR_PATH, IMAGE_EXTENSION, SIDECAR_EXTENSION)
End Sub
Private Sub GetFilesInDirectory(ByVal path As String, ByVal photoExtension As String, ByVal sidecarExtension As String)
Const EXTENSION_LENGTH As Integer = 4
Dim arrayOfFiles() As String = Directory.GetFiles(path, "*" & photoExtension)
Dim baseName As String
Dim photoFileName As String
Dim sidecarFileName As String
Dim originalDate As String
For arrayIndex As Integer = 0 To arrayOfFiles.Length - 1
photoFileName = arrayOfFiles(arrayIndex)
baseName = photoFileName.Substring(0, photoFileName.Length - EXTENSION_LENGTH)
sidecarFileName = baseName & sidecarExtension
If File.Exists(sidecarFileName) Then
originalDate = GetFileDate(sidecarFileName)
RenamePhotoFiles(baseName, originalDate, photoExtension, sidecarExtension)
End If
Next
End Sub
Private Function GetFileDate(ByVal sidecarFile As String) As String
Const LINE_START As String = " exif:DateTimeOriginal="
Const DATE_STRING_LENGTH As Integer = 10
Const CHAR_TO_REMOVE As String = "-"
Dim lines = File.ReadAllLines(sidecarFile)
Dim targetData As String = Nothing
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith(LINE_START) Then
targetData = lines(i)
Exit For
End If
Next
targetData = targetData.Substring(LINE_START.Length + 1, DATE_STRING_LENGTH)
GetFileDate = targetData.Replace(CHAR_TO_REMOVE, "")
End Function
Private Sub RenamePhotoFiles(ByVal oldName As String, ByVal fileDate As String, ByVal photoExtension As String, ByVal sidecarExtension As String)
Const FILE_EXTENDER As String = "_"
Dim newName As String = oldName & FILE_EXTENDER & fileDate
File.Move(oldName & photoExtension, newName & photoExtension)
File.Move(oldName & sidecarExtension, newName & sidecarExtension)
End Sub
End Module