Created
October 23, 2016 20:27
-
-
Save jzeferino/de7e5acc4e8db98e8dfefa5f028b1c9c to your computer and use it in GitHub Desktop.
Load T from resources Xamarin - Note: mark file build action as embedresource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Reflection; | |
using Newtonsoft.Json; | |
using System.Linq; | |
using System.Runtime.InteropServices.ComTypes; | |
namespace jzeferino.gist | |
{ | |
public static class LocalJsonLoader | |
{ | |
public static T LoadJsonResource<T>(string filename) | |
{ | |
var assembly = typeof(LocalJsonLoader).GetTypeInfo().Assembly; | |
var resourceName = Array.Find(assembly.GetManifestResourceNames(), resource => resource.Contains(filename)); | |
if (string.IsNullOrEmpty(resourceName)) | |
{ | |
throw new FileNotFoundException($"{filename} not found."); | |
} | |
Stream stream = assembly.GetManifestResourceStream(resourceName); | |
using (var reader = new StreamReader(stream)) | |
{ | |
var json = reader.ReadToEnd(); | |
return JsonConvert.DeserializeObject<T>(json); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment