Reading contents of SVG from azure blob storage ?
# help-with-umbraco
s
I have this small helper code that works fine locally, but on Umbraco Cloud it returns nothing.
Copy code
public HtmlString RenderSVGInline(MediaWithCrops svg) {
    string webRootPath = _webHostEnvironment.WebRootPath;
    string url = svg.Url();
    string path = $"{webRootPath}{url}";
    string toReturn = string.Empty;
    try {
        if (System.IO.File.Exists(path)) {
            toReturn = System.IO.File.ReadAllText(path);
            if (!string.IsNullOrWhiteSpace(toReturn) && toReturn.IndexOf("<svg") > 0) {
                toReturn = toReturn.Substring(toReturn.IndexOf("<svg"));
            }
        }
    } catch (Exception ex) {
        return new HtmlString("<span style=\"background:#f998;color:#000;\">" + ex.ToString() + "</span>");
    }
    return new HtmlString(toReturn);
}
So I guess it has something to do with Cloud using Azure Blob Storage. How to I make this work both locally and on Umbraco Cloud ?
a
Hi Seb I think I rewrote some of your code to use Umbraco's media file system instead of downloading the media via
WebClient
or
HttpClient
, so this is what I have:
Copy code
csharp
    private string GetContentsFromFileSystem(IPublishedContent media) {

        try {

            // Open a new stream to the file (on disk, in blob storage or similar)
            using Stream stream = _mediaFileManager.FileSystem.OpenFile(media.Url());

            // Create a new stream reader around the stream
            using StreamReader reader = new(stream, Encoding.UTF8);

            // Read to the end of the stream
            string contents = reader.ReadToEnd();

            // Return the file contents
            return contents;

        } catch (Exception ex) {

            // TODO: implement better exception handling
            throw new Exception("MEH: " + media.Url(), ex);

        }

    }
Where
_mediaFileManager
is an instance of
Umbraco.Cms.Core.IO.MediaFileManager
. The media file system is an abstraction of whatever is used (local disk, blob storage etc.), so this will work with different setups. But like we've discussed previously, this should be used with caution as there will be a performance penalty in downloading the file from blob storage. I ended op building a cache layer on top of this method.
s
Ahhh, yeah I remember that we discussed this 🙂 Thanks
6 Views