Tuesday, April 9, 2013

Automatic file naming code snippet

For some applications, it can be useful to be able to save a file without asking for a filename first with a dialog. Much like e.g. taking a screenshot on a Mac, this ends up on the Desktop with a filename that contains the time of the file, e.g. "Screen shot 2013-04-09 at 10:10 AM".

This code snippet generates a FolderItem with a filename generated in the same way:

Function AutonamedFile(prefix As String, extension As String) As FolderItem
  Dim f As FolderItem
  Dim D As Date
  Dim i As Integer
  
  D = New Date
  
  f = SpecialFolder.Desktop.Child(prefix + D.SQLDate+ " at " + Format(D.Hour,"00")+"."+Format(D.Minute,"00")+"."+Format(D.Second,"00")+ "."+extension)
  
  If f.Exists Then
    i = 1
    Do
      f = SpecialFolder.Desktop.Child(prefix + D.SQLDate+ " at " + Format(D.Hour,"00")+"."+Format(D.Minute,"00")+"."+Format(D.Second,"00")+" " + Str(i)+ "."+extension)
      i = i+1
    Loop Until Not f.Exists
  End if
  
  Return f
  
End Function


Copy-paste into RealStudio as a method. For saving e.g. a Picture (MyPicture) the same way that the screenshot function in the Mac does it, call with the prefix and extension like so:

Dim f As FolderItem

f = AutonamedFile("Screen shot", "png")
MyPicture.Save(f, Picture.SaveAsPNG)


No comments:

Post a Comment