Sebastian Dammark
11/29/2024, 2:49 PMpublic 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 ?Anders Bjerner
11/29/2024, 3:24 PMWebClient
or HttpClient
, so this is what I have:
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.