Search code examples
tridion

Get full name of binary from Razor Template, including extention


I'm using a technique I found on SO (here) to publish binaries from a Razor template. It works great except for one minor shortcoming.

I want to push an item with the file name that was uploaded to Tridion. I can use the title for most of that, but how can I determine the file extension? In this case I need to know the name of the file in the template because I am going to do some javascript manipulation with it.

Again, everything works fine, but I'd like to do something other than just concatenating a ".jpg". It looks like I can parse the WebDavUrl property. Is that my only option?

@{ 
  var item1 = TridionHelper.Package.CreateMultimediaItem(@Fields.closed.ID);
  TridionHelper.Package.PushItem(@Fields.closed.Title + ".jpg", item1);

  string closed = @Publication.MultimediaUrl + "/"+(@Fields.closed.Title) + ".jpg";

}

Solution

  • You have full access to the TOM.NET API from Razor Mediator, so you can also access the filename from the Component's BinaryContent field. Assuming @Fields.closed is a Multimedia Component Link you can do:

    @Fields.closed.TridionObject.BinaryContent.Filename
    

    Note that this will be the original path/filename that was uploaded. You also have access to System.IO.Path, so you co:

    @System.IO.Path.GetFileName(Fields.closed.TridionObject.BinaryContent.Filename)
    @System.IO.Path.GetExtension(Fields.closed.TridionObject.BinaryContent.Filename)
    @System.IO.Path.GetFileNameWithoutExtensions(Fields.closed.TridionObject.BinaryContent.Filename)
    

    You'll have to be careful if you have a custom TBB that publishes binaries, as this TBB could actually change the filename that is published, and the Filename property of BinaryContent will only contain the original uploaded path and filename.