Here are the examples of the csharp api System.Reflection.Assembly.GetManifestResourceNames() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
532 Examples
19
Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam
with GNU General Public License v3.0
from 0dteam
private static string GetResourceText(string resourceName)
{
replacedembly asm = replacedembly.GetExecutingreplacedembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
19
Source : TerrariaHooksManager.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
internal static ModuleDefinition GenerateCecilModule(replacedemblyName name) {
replacedemblyName UnwrapName(replacedemblyName other) {
int underscore = other.Name.LastIndexOf('_');
if (underscore == -1)
return other;
other.Name = other.Name.Substring(0, underscore);
return other;
}
// Terraria ships with some dependencies as embedded resources.
string resourceName = name.Name + ".dll";
resourceName = Array.Find(typeof(Program).replacedembly.GetManifestResourceNames(), element => element.EndsWith(resourceName));
if (resourceName != null) {
using (Stream stream = typeof(Program).replacedembly.GetManifestResourceStream(resourceName))
// Read immediately, as the stream isn't open forever.
return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
}
// Mod .dlls exist in the mod's .tmod containers.
string nameStr = name.ToString();
foreach (Mod mod in ModLoader.LoadedMods) {
if (mod.Code == null || mod.File == null)
continue;
// Check if it's the main replacedembly.
if (mod.Code.GetName().ToString() == nameStr) {
// Let's unwrap the name and cache it for all DMDs as well.
// tModLoader changes the replacedembly name to allow mod updates, which breaks replacedembly.Load
ReflectionHelper.replacedemblyCache[UnwrapName(mod.Code.GetName()).ToString()] = mod.Code;
using (MemoryStream stream = new MemoryStream(mod.File.GetMainreplacedembly()))
// Read immediately, as the stream isn't open forever.
return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
}
// Check if the replacedembly is possibly included in the .tmod
if (!mod.Code.GetReferencedreplacedemblies().Any(other => UnwrapName(other).ToString() == nameStr))
continue;
// Try to load lib/Name.dll
byte[] data;
if ((data = mod.File.GetFile($"lib/{name.Name}.dll")) != null)
using (MemoryStream stream = new MemoryStream(data))
// Read immediately, as the stream isn't open forever.
return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
}
return null;
}
19
Source : RedumpProvider.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
var result = new HashSet<DiscKeyInfo>();
try
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
if (embeddedResources.Any())
Log.Trace("Loading embedded redump keys");
else
Log.Warn("No embedded redump keys found");
foreach (var res in embeddedResources)
{
using var resStream = replacedembly.GetManifestResourceStream(res);
using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
|| e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
{
using var keyStream = zipEntry.Open();
using var memStream = new MemoryStream();
await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
var discKey = memStream.ToArray();
if (zipEntry.Length > 256/8*2)
{
Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
continue;
}
if (discKey.Length > 16)
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
try
{
result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
}
catch (Exception e)
{
Log.Warn(e, $"Invalid disc key format: {discKey}");
}
}
}
if (result.Any())
Log.Info($"Found {result.Count} embedded redump keys");
else
Log.Warn($"Failed to load any embedded redump keys");
}
catch (Exception e)
{
Log.Error(e, "Failed to load embedded redump keys");
}
Log.Trace("Loading cached redump keys");
var diff = result.Count;
try
{
if (Directory.Exists(discKeyCachePath))
{
var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
.Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
foreach (var dkeyFile in matchingDiskKeys)
{
try
{
try
{
var discKey = File.ReadAllBytes(dkeyFile);
if (discKey.Length > 16)
{
try
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
catch (Exception e)
{
Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
}
}
result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
}
catch (InvalidDataException)
{
File.Delete(dkeyFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
}
catch (Exception ex)
{
Log.Warn(ex, "Failed to load redump keys from local cache");
}
diff = result.Count - diff;
Log.Info($"Found {diff} cached disc keys");
return result;
}
19
Source : XmlCommandsProvider.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
public void Load(System.Reflection.replacedembly replacedembly)
{
var filenames = replacedembly.GetManifestResourceNames();
foreach (var item in filenames)
{
if (!item.EndsWith(".xml", System.StringComparison.OrdinalIgnoreCase))
{
continue;
}
Load(replacedembly.GetManifestResourceStream(item));
}
}
19
Source : XmlCommandsProvider.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
public void Load(System.Reflection.replacedembly replacedembly, string pattern)
{
var filenames = replacedembly.GetManifestResourceNames();
foreach (var item in filenames)
{
if (!Regex.IsMatch(item, pattern))
{
continue;
}
Load(replacedembly.GetManifestResourceStream(item));
}
}
19
Source : LanguageHelper.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private string GetFileContents(string filename)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
string resourceName = replacedembly.GetManifestResourceNames().Single(str => str.EndsWith(filename));
using (Stream stream = replacedembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
19
Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static AudioClip GetAudioClip(string name)
{
string[] wavNames = replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
foreach(var wav in wavNames)
{
Stream stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(wav);
var split = wav.Split('.');
string intername = split[split.Length - 2];
if(intername == name)
{
byte[] buf = new byte[stream.Length];
stream.Read(buf, 0, buf.Length);
return WavUtility.ToAudioClip(buf, 0, intername);
}
}
return null;
}
19
Source : ObjectManager.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static void Load()
{
if (loaded)
return;
string[] resourceNames = replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
foreach (string res in resourceNames)
{
Logger.LogDebug($"Find Embeded Resource:{res}");
if (res.EndsWith(".png"))
{
try
{
Stream imageStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(res);
byte[] buffer = new byte[imageStream.Length];
imageStream.Read(buffer, 0, buffer.Length);
string[] split = res.Split('.');
string internalName = split[split.Length - 2];
if (res.Contains("images.objects"))
{
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(buffer.ToArray());
images.Add(internalName, tex);
}
else
{
raw_images.Add(internalName, buffer);
}
}
catch
{
loaded = false;
}
}
}
loaded = true;
}
19
Source : UserLicense.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static void ShowLicense()
{
if(!agreeLicense)
{
string bundleN = "userlicense";
replacedetBundle ab = null; // You probably want this to be defined somewhere more global.
replacedembly asm = replacedembly.GetExecutingreplacedembly();
foreach (string res in asm.GetManifestResourceNames())
{
using (Stream s = asm.GetManifestResourceStream(res))
{
if (s == null) continue;
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, buffer.Length);
s.Dispose();
string bundleName = Path.GetExtension(res).Substring(1);
if (bundleName != bundleN) continue;
Logger.Log("Loading bundle " + bundleName);
ab = replacedetBundle.LoadFromMemory(buffer); // Store this somewhere you can access again.
}
}
var _canvas = ab.Loadreplacedet<GameObject>("userlicense");
UnityEngine.Object.Instantiate(_canvas);
Logger.Log("Show User License");
}
}
19
Source : DatabaseSchemaUpgradeManager.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
private static int GetLatestVersion()
{
string startsWith = $"{Thisreplacedembly.RootNamespace}.SchemaUpgradeScripts.";
string endsWith = ".sql";
int latestVersion = (from name in replacedembly.GetExecutingreplacedembly().GetManifestResourceNames()
where name.StartsWith(startsWith, StringComparison.Ordinal) && name.EndsWith(endsWith, StringComparison.Ordinal)
let version = int.Parse(name.Substring(startsWith.Length, name.Length - startsWith.Length - endsWith.Length), CultureInfo.InvariantCulture)
select version).Max();
return latestVersion;
}
19
Source : ExampleLoader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static string LoadSourceFile(string name)
{
replacedembly replacedembly = typeof(ExampleLoader).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var allExampleSourceFiles = names.Where(x => x.Contains("SciChart.Examples.Examples"));
var find = name.Replace('/', '.').Replace(".txt", string.Empty).Replace("Resources.ExampleSourceFiles.", string.Empty);
var file = allExampleSourceFiles.FirstOrDefault(x => x.EndsWith(find));
if (file == null)
throw new Exception(string.Format("Unable to find the source code resource {0}", find));
using (var s = replacedembly.GetManifestResourceStream(file))
using (var sr = new StreamReader(s))
{
return sr.ReadToEnd();
}
}
19
Source : ExampleLoader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private IDictionary<ExampleKey, string> DiscoverAllExampleDefinitions()
{
var dict = new Dictionary<ExampleKey, string>();
replacedembly replacedembly = typeof (ExampleLoader).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var allXmlManifestResources = names.Where(x => x.Contains("ExampleDefinitions")).ToList();
allXmlManifestResources.Sort();
foreach(var xmlResource in allXmlManifestResources)
{
using (var s = replacedembly.GetManifestResourceStream(xmlResource))
using (var sr = new StreamReader(s))
{
string exampleKeyString = xmlResource.Replace("SciChart.Examples.Resources.ExampleDefinitions.", string.Empty)
.Replace("SciChart.Examples.SL.Resources.ExampleDefinitions.", string.Empty);
string[] chunks = exampleKeyString.Split('.');
var exampleKey = new ExampleKey()
{
ExampleCategory = Trim(chunks[0], true),
ChartGroup = Trim(chunks[1]),
Examplereplacedle = Trim(chunks[2])
};
dict.Add(exampleKey, sr.ReadToEnd());
}
}
return dict;
}
19
Source : ExampleManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static IDictionary<string, string> GetAllExampleDefinitions()
{
var dictionary = new Dictionary<string, string>();
var replacedembly = typeof(ExampleManager).replacedembly;
var exampleNames = replacedembly.GetManifestResourceNames().Where(x => x.Contains("ExampleSourceFiles")).ToList();
exampleNames.Sort();
foreach (var example in exampleNames)
{
using (var s = replacedembly.GetManifestResourceStream(example))
using (var sr = new StreamReader(s))
{
dictionary.Add(example.Replace("SciChart.Example.Resources.ExampleDefinitions.", string.Empty),
sr.ReadToEnd());
}
}
return dictionary;
}
19
Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static void ExportIndexToHtml(IModule module)
{
var replacedembly = typeof(HtmlExportHelper).replacedembly;
string[] names = replacedembly.GetManifestResourceNames();
var templateFile = names.SingleOrDefault(x => x.Contains(IndexTemplateFileName));
using (var s = replacedembly.GetManifestResourceStream(templateFile))
using (var sr = new StreamReader(s))
{
string lines = sr.ReadToEnd();
StringBuilder sb = new StringBuilder();
foreach (var categoryGroup in module.Examples.Values.GroupBy(x => x.TopLevelCategory))
{
sb.Append("<h2>").Append(categoryGroup.Key).Append("</h2>").Append(Environment.NewLine);
foreach (var exampleGroup in categoryGroup.GroupBy(x => x.Group))
{
sb.Append("<h4>").Append(exampleGroup.Key).Append("</h4>").Append(Environment.NewLine);
sb.Append("<ul>").Append(Environment.NewLine);
foreach (var example in exampleGroup)
{
var fileName = string.Format("wpf-{0}chart-example-{1}",
example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
example.replacedle.ToLower().Replace(" ", "-"));
sb.Append("<li>").Append("<a href=\"").Append(fileName).Append("\">").Append(example.replacedle).Append("</a></li>");
}
sb.Append("</ul>").Append(Environment.NewLine);
}
}
lines = lines.Replace("[Index]", sb.ToString());
File.WriteAllText(Path.Combine(ExportPath, "wpf-chart-examples.html"), lines);
}
}
19
Source : ProjectWriter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static string WriteProject(Example example, string selectedPath, string replacedembliesPath, bool showMessageBox = true)
{
var files = new Dictionary<string, string>();
var replacedembly = typeof(ProjectWriter).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var templateFiles = names.Where(x => x.Contains("Templates")).ToList();
foreach (var templateFile in templateFiles)
{
var fileName = GetFileNameFromNs(templateFile);
using (var s = replacedembly.GetManifestResourceStream(templateFile))
{
if (s == null) break;
using (var sr = new StreamReader(s))
{
files.Add(fileName, sr.ReadToEnd());
}
}
}
string projectName = "SciChart_" + Regex.Replace(example.replacedle, @"[^A-Za-z0-9]+", string.Empty);
files[ProjectFileName] = GenerateProjectFile(files[ProjectFileName], example, replacedembliesPath);
files[SolutionFileName] = GenerateSolutionFile(files[SolutionFileName], projectName);
files.RenameKey(ProjectFileName, projectName + ".csproj");
files.RenameKey(SolutionFileName, projectName + ".sln");
files[MainWindowFileName] = GenerateShellFile(files[MainWindowFileName], example).Replace("[Examplereplacedle]", example.replacedle);
foreach (var codeFile in example.SourceFiles)
{
files.Add(codeFile.Key, codeFile.Value);
}
WriteProjectFiles(files, Path.Combine(selectedPath, projectName));
if (showMessageBox && Application.Current.MainWindow != null)
{
var message = $"The {example.replacedle} example was successfully exported to {selectedPath + projectName}";
MessageBox.Show(Application.Current.MainWindow, message, "Success!");
}
return projectName;
}
19
Source : AutomationTestBase.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public WriteableBitmap LoadResource(string resourceName)
{
resourceName = resourceName.Replace("/", ".");
WriteableBitmap expectedBitmap = null;
var replacedembly = GetType().replacedembly;
// For testing purposes, to see all the resources available
var resourcePath = replacedembly.GetManifestResourceNames().FirstOrDefault(x => x.ToUpper().Contains(resourceName.ToUpper()));
using (var resourceStream = replacedembly.GetManifestResourceStream(resourcePath))
{
expectedBitmap = Path.GetExtension(resourceName).ToUpper() == ".BMP"
? DecodeBmpStream(resourceStream)
: DecodePngStream(resourceStream);
}
return expectedBitmap;
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static string[] GetStopWords(string fileName, char splitter)
{
replacedembly replacedembly = typeof (CreateInvertedIndex).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var allExampleSourceFiles = names.Where(x => x.Contains(fileName));
var file = allExampleSourceFiles.FirstOrDefault();
var result = new string[] {};
if (file != null)
{
using (var s = replacedembly.GetManifestResourceStream(file))
using (var sr = new StreamReader(s))
{
var readToEnd = sr.ReadToEnd();
result = readToEnd.Split(splitter);
result = result.Select(x =>
{
if (x.Contains("\n"))
return x.Replace("\n", "");
return x;
}).ToArray();
}
}
return result;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public IEnumerable<TimeFrame> GetAvailableTimeFrames(Instrument forInstrument)
{
if (_availableTimeFrames == null)
{
lock (typeof (DataManager))
{
if (_availableTimeFrames == null)
{
// Initialise the Timeframe dictionary
_availableTimeFrames = new Dictionary<Instrument, IList<TimeFrame>>();
foreach (var instr in AvailableInstruments)
{
_availableTimeFrames[instr] = new List<TimeFrame>();
}
var replacedembly = typeof (DataManager).replacedembly;
foreach (var resourceString in replacedembly.GetManifestResourceNames())
{
if (resourceString.Contains("_"))
{
var instrument = Instrument.Parse(GetSubstring(resourceString, ResourceDirectory + ".", "_"));
var timeframe = TimeFrame.Parse(GetSubstring(resourceString, "_", ".csv.gz"));
_availableTimeFrames[instrument].Add(timeframe);
}
}
}
}
}
return _availableTimeFrames[forInstrument];
}
19
Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void ExportExampleToHtml(Example example, bool isUniqueExport = true)
{
if (isUniqueExport)
{
if (!GetPathForExport())
{
MessageBox.Show("Bad path. Please, try export once more.");
return;
}
}
var replacedembly = typeof (HtmlExportHelper).replacedembly;
string[] names = replacedembly.GetManifestResourceNames();
var templateFile = names.SingleOrDefault(x => x.Contains(TemplateFileName));
using (var s = replacedembly.GetManifestResourceStream(templateFile))
using (var sr = new StreamReader(s))
{
string lines = sr.ReadToEnd();
var exampleFolderPath = ExportPath;//string.Format("{0}{1}\\", ExportPath, example.replacedle);
//CreateExampleFolder(exampleFolderPath);
PrintMainWindow("scichart-wpf-chart-example-" + example.replacedle.ToLower().Replace(" ", "-"), exampleFolderPath);
lines = ReplaceTagsWithExample(lines, example);
var fileName = string.Format("wpf-{0}chart-example-{1}.html",
example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
example.replacedle.ToLower().Replace(" ", "-"));
File.WriteAllText(Path.Combine(ExportPath, fileName), lines);
}
}
19
Source : AscReader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static async Task<AscData> ReadResourceToAscData(
string resourceName, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
{
var result = await Task.Run(() =>
{
var asm = replacedembly.GetExecutingreplacedembly();
var resource = asm.GetManifestResourceNames()
.Single(x => x.Contains(resourceName));
using (var stream = asm.GetManifestResourceStream(resource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
return ReadFromStream(streamReader, colorMapFunction, reportProgress);
}
});
return result;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public IEnumerable<TradeData> GetTradeticks()
{
var dataSource = new List<TradeData>();
var asm = replacedembly.GetExecutingreplacedembly();
var csvResource = asm.GetManifestResourceNames().Single(x => x.ToUpper(CultureInfo.InvariantCulture).Contains("TRADETICKS.CSV.GZ"));
using (var stream = asm.GetManifestResourceStream(csvResource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var data = new TradeData();
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
data.TradeDate = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
data.TradePrice = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
data.TradeSize = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
dataSource.Add(data);
line = streamReader.ReadLine();
}
}
return dataSource;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public List<WeatherData> LoadWeatherData()
{
var values = new List<WeatherData>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("WeatherData.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var tokens = line.Split(',');
values.Add(new WeatherData
{
// ID, Date, MinTemp, MaxTemp, Rainfall, Sunshine, UVIndex, WindSpd, WindDir, Forecast, LocalStation
ID = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo),
Date = DateTime.Parse(tokens[1], DateTimeFormatInfo.InvariantInfo),
MinTemp = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo),
MaxTemp = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo),
Rainfall = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo),
Sunshine = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo),
UVIndex = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo),
WindSpeed = int.Parse(tokens[7], NumberFormatInfo.InvariantInfo),
WindDirection = (WindDirection) Enum.Parse(typeof(WindDirection), tokens[8]),
Forecast = tokens[9],
LocalStation = bool.Parse(tokens[10])
});
line = streamReader.ReadLine();
}
}
return values;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public double[] LoadWaveformData()
{
var values = new List<double>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("Waveform.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
Source : SweepingEcg.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private double[] LoadWaveformData(string filename)
{
var values = new List<double>();
// Load the waveform.csv file for the source data
var asm = typeof (SweepingEcg).replacedembly;
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains(filename));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var streamReader = new StreamReader(stream))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
Source : MutationCache.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void CacheResourceNames()
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var resourceNames = replacedembly.GetManifestResourceNames();
foreach (var resourceName in resourceNames)
{
var pieces = resourceName.Split('.');
if (pieces.Length < 2)
{
log.Error($"MutationCache.CacheResourceNames() - unknown resource format {resourceName}");
continue;
}
var shortName = pieces[pieces.Length - 2];
var match = Regex.Match(shortName, @"([0-9A-F]{8})");
if (match.Success && uint.TryParse(match.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var mutationId))
mutationIdToFilename[mutationId] = resourceName.Replace(prefix, "");
}
}
19
Source : Resources.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public static Stream GetEmbeddedResourceStream(string name, replacedembly replacedembly = null)
{
var asm = replacedembly ?? replacedembly.GetCallingreplacedembly();
var resourceNames = asm.GetManifestResourceNames();
var match = resourceNames.FirstOrDefault(n => n.EndsWith(name));
if (match == null) throw new ArgumentException($"Embedded resource '{name}' not found.", nameof(name));
return asm.GetManifestResourceStream(match);
}
19
Source : EmbeddedResourceXmlSchemaProvider.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
protected virtual string GetSchemaResourceFullName(replacedembly curentreplacedembly) =>
curentreplacedembly.GetManifestResourceNames()
?.FirstOrDefault(rName => rName.EndsWith(SharedConstants.SuppressionFileXmlSchemaFileName));
19
Source : AssemblyExtensions.cs
with MIT License
from adamfisher
with MIT License
from adamfisher
public static bool ContainsManifestResource(this replacedembly replacedembly, string resourceName)
{
return replacedembly != null
&& replacedembly.GetManifestResourceNames()
.Any(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
}
19
Source : AssemblyExtensions.cs
with MIT License
from adamfisher
with MIT License
from adamfisher
public static Stream GetEmbeddedResourceStream(this replacedembly replacedembly, string resourceFileName)
{
var resourceNames = replacedembly.GetManifestResourceNames();
var resourcePaths = resourceNames
.Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (!resourcePaths.Any())
{
throw new Exception($"Resource ending with {resourceFileName} not found.");
}
if (resourcePaths.Count() > 1)
{
throw new Exception($"Multiple resources ending with {resourceFileName} found: {Environment.NewLine}{string.Join(Environment.NewLine, resourcePaths)}");
}
return replacedembly.GetManifestResourceStream(resourcePaths.Single());
}
19
Source : VideoSource.cs
with MIT License
from adamfisher
with MIT License
from adamfisher
public static VideoSource FromResource(string resource, replacedembly replacedembly = default(replacedembly))
{
if (string.IsNullOrEmpty (resource))
return null;
if (!Path.HasExtension (resource))
throw new Exception ($"The specified resource '{resource}' must contain a valid file extension.");
var foundResource = false;
var format = Path.GetExtension (resource)?.Replace (".", string.Empty);
replacedembly parameterreplacedembly = null, callingreplacedembly = null, entryreplacedembly = null;
if (replacedembly != null)
{
parameterreplacedembly = replacedembly;
foundResource = replacedembly.ContainsManifestResource(resource);
}
if (!foundResource)
{
replacedembly = replacedembly.GetCallingreplacedembly();
callingreplacedembly = replacedembly;
foundResource = replacedembly.ContainsManifestResource(resource);
}
if (!foundResource)
{
replacedembly = replacedembly.GetEntryreplacedembly();
entryreplacedembly = replacedembly;
foundResource = replacedembly.ContainsManifestResource(resource);
}
if (!foundResource)
{
var resourceNames = new List<string>();
if (parameterreplacedembly != null)
resourceNames.AddRange(parameterreplacedembly.GetManifestResourceNames());
if (callingreplacedembly != null)
resourceNames.AddRange(callingreplacedembly.GetManifestResourceNames());
if (entryreplacedembly != null)
resourceNames.AddRange(entryreplacedembly.GetManifestResourceNames());
Log.Error($"Unable to locate the embedded resource '{resource}'. " +
$"Possible candidates are: {Environment.NewLine}{string.Join(Environment.NewLine, resourceNames)}");
return null;
}
return FromStream(() => replacedembly.GetEmbeddedResourceStream(resource), format);
}
19
Source : EmbeddedResourceFileSystem.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IEnumerable<TemplateFileInfo> GetTemplateFiles()
{
return replacedembly.GetManifestResourceNames()
.Select(name => new { Resource = name, Match = _resourceRegex.Match(name) })
.Where(e => e.Match.Success)
.GroupBy(e => e.Match.Groups["name"].Value, e => e.Resource, StringComparer.InvariantCulture)
.Select(e => new TemplateFileInfo(e.Key.Replace(".", "/"), GetTemplateMetadata(e)))
.ToArray();
}
19
Source : ContractsDeployer.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private static IEnumerable<string> GetContractNames(replacedembly replacedembly)
{
var manifestName = "Contracts.manifest";
var resourceName = replacedembly.GetManifestResourceNames().FirstOrDefault(n => n.EndsWith(manifestName));
if (resourceName == default)
{
return new string[0];
}
using var stream = replacedembly.GetManifestResourceStream(resourceName);
using var reader = new StreamReader(stream);
var result = reader.ReadToEnd();
return result.Trim().Split('\n').Select(f => f.Trim()).ToArray();
}
19
Source : ImageResourceExtension.cs
with MIT License
from aimore
with MIT License
from aimore
public static string ImageNameFromResource(string u)
{
var replacedembly = typeof(App).GetTypeInfo().replacedembly;
foreach (var res in replacedembly.GetManifestResourceNames())
{
// System.Diagnostics.Debug.WriteLine("found resource: " + res);
if (res.Contains(u))
{
return res;
}
}
return null;
}
19
Source : CommonUtils.cs
with GNU Affero General Public License v3.0
from akshinmustafayev
with GNU Affero General Public License v3.0
from akshinmustafayev
public static string ReadreplacedemblyFile(string name)
{
// Determine path
var replacedembly = replacedembly.GetExecutingreplacedembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(EasyJob)))
{
resourcePath = replacedembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = replacedembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
19
Source : Ring0.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private static bool ExtractDriver(string fileName) {
string resourceName = "OpenHardwareMonitor.Hardware." +
(OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :
"WinRing0.sys");
string[] names = Getreplacedembly().GetManifestResourceNames();
byte[] buffer = null;
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == resourceName) {
using (Stream stream = Getreplacedembly().
GetManifestResourceStream(names[i]))
{
buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
}
}
}
if (buffer == null)
return false;
try {
using (FileStream target = new FileStream(fileName, FileMode.Create)) {
target.Write(buffer, 0, buffer.Length);
target.Flush();
}
} catch (IOException) {
// for example there is not enough space on the disk
return false;
}
// make sure the file is actually writen to the file system
for (int i = 0; i < 20; i++) {
try {
if (File.Exists(fileName) &&
new FileInfo(fileName).Length == buffer.Length)
{
return true;
}
Thread.Sleep(100);
} catch (IOException) {
Thread.Sleep(10);
}
}
// file still has not the right size, something is wrong
return false;
}
19
Source : EmbeddedResources.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static Image GetImage(string name) {
name = "OpenHardwareMonitor.Resources." + name;
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
// "You must keep the stream open for the lifetime of the Image."
Image image = Image.FromStream(stream);
// so we just create a copy of the image
Bitmap bitmap = new Bitmap(image);
// and dispose it right here
image.Dispose();
return bitmap;
}
}
}
return new Bitmap(1, 1);
}
19
Source : HttpServer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void ServeResourceImage(HttpListenerResponse response, string name) {
name = "OpenHardwareMonitor.Resources." + name;
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
Image image = Image.FromStream(stream);
response.ContentType = "image/png";
try {
Stream output = response.OutputStream;
using (MemoryStream ms = new MemoryStream()) {
image.Save(ms, ImageFormat.Png);
ms.WriteTo(output);
}
output.Close();
} catch (HttpListenerException) {
}
image.Dispose();
response.Close();
return;
}
}
}
response.StatusCode = 404;
response.Close();
}
19
Source : EmbeddedResources.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static Icon GetIcon(string name) {
name = "OpenHardwareMonitor.Resources." + name;
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
return new Icon(stream);
}
}
}
return null;
}
19
Source : HttpServer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void ServeResourceFile(HttpListenerResponse response, string name,
string ext)
{
// resource names do not support the hyphen
name = "OpenHardwareMonitor.Resources." +
name.Replace("custom-theme", "custom_theme");
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
response.ContentType = GetcontentType("." + ext);
response.ContentLength64 = stream.Length;
byte[] buffer = new byte[512 * 1024];
int len;
try {
Stream output = response.OutputStream;
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
output.Write(buffer, 0, len);
}
output.Flush();
output.Close();
response.Close();
} catch (HttpListenerException) {
} catch (InvalidOperationException) {
}
return;
}
}
}
response.StatusCode = 404;
response.Close();
}
19
Source : Utils.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public static string GetEmbeddedStringResource(replacedembly replacedembly, string resourceName)
{
string result = null;
// Use the .NET procedure for loading a file embedded in the replacedembly
Stream stream = replacedembly.GetManifestResourceStream(resourceName);
if (stream != null)
{
// Convert bytes to string
byte[] fileContentsAsBytes = new byte[stream.Length];
stream.Read(fileContentsAsBytes, 0, (int)stream.Length);
result = Encoding.Default.GetString(fileContentsAsBytes);
}
else
{
// Embedded resource not found - list available resources
Debug.WriteLine("Unable to find the embedded resource file '" + resourceName + "'.");
Debug.WriteLine(" Available resources:");
foreach (string aResourceName in replacedembly.GetManifestResourceNames())
{
Debug.WriteLine(" " + aResourceName);
}
}
return result;
}
19
Source : HotReloader.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private async void InitializeElement(object obj, bool hasCodeGenAttr, bool isInjected = false)
{
if (obj == null)
{
return;
}
if (obj is Cell cell && _ignoredElementInit != obj)
{
cell.PropertyChanged += OnCellPropertyChanged;
}
var elementType = obj.GetType();
var clreplacedName = RetrieveClreplacedName(elementType);
if (!_resourceMapping.TryGetValue(clreplacedName, out ReloadItem item))
{
item = new ReloadItem { HasXaml = hasCodeGenAttr };
_resourceMapping[clreplacedName] = item;
if (item.HasXaml)
{
var type = obj.GetType();
var getXamlForType = XamlLoaderType.GetMethod("GetXamlForType", BindingFlags.Static | BindingFlags.NonPublic);
string xaml = null;
try
{
var length = getXamlForType?.GetParameters()?.Length;
if (length.HasValue)
{
switch (length.Value)
{
case 1:
xaml = getXamlForType.Invoke(null, new object[] { type })?.ToString();
break;
case 2:
xaml = getXamlForType.Invoke(null, new object[] { type, true })?.ToString();
break;
case 3:
getXamlForType.Invoke(null, new object[] { type, obj, true })?.ToString();
break;
}
}
}
catch
{
//suppress
}
if (xaml != null)
{
item.Xaml.LoadXml(xaml);
}
else
{
var stream = type.replacedembly.GetManifestResourceStream(type.FullName + ".xaml");
try
{
if (stream == null)
{
var appResName = type.replacedembly.GetManifestResourceNames()
.FirstOrDefault(x => (x.Contains("obj.Debug.") || x.Contains("obj.Release")) && x.Contains(type.Name));
if (!string.IsNullOrWhiteSpace(appResName))
{
stream = type.replacedembly.GetManifestResourceStream(appResName);
}
}
if (stream != null && stream != Stream.Null)
{
using (var reader = new StreamReader(stream))
{
xaml = reader.ReadToEnd();
item.Xaml.LoadXml(xaml);
}
}
}
finally
{
stream?.Dispose();
}
}
}
}
if (!(obj is ResourceDictionary))
{
item.Objects.Add(obj);
}
if (_ignoredElementInit == obj)
{
return;
}
if (!item.HasUpdates && !isInjected)
{
OnLoaded(obj, false);
}
else
{
var code = item.Code;
if (isInjected)
{
code = code?.Replace("HotReloader.Current.InjectComponentInitialization(this)", string.Empty);
}
var csharpType = !string.IsNullOrWhiteSpace(item.Code) ? HotCompiler.Current.Compile(item.Code, obj.GetType().FullName) : null;
if (csharpType != null)
{
await Task.Delay(50);
}
ReloadElement(obj, item, csharpType);
}
}
19
Source : Certificate.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public static X509Certificate2 Get()
{
var replacedembly = typeof(Certificate).GetTypeInfo().replacedembly;
var names = replacedembly.GetManifestResourceNames();
/***********************************************************************************************
* Please note that here we are using a local certificate only for testing purposes. In a
* real environment the certificate should be created and stored in a secure way, which is out
* of the scope of this project.
**********************************************************************************************/
using (var stream = replacedembly.GetManifestResourceStream("Idenreplacedy.API.Certificate.idsrv3test.pfx"))
{
return new X509Certificate2(ReadStream(stream), "idsrv3test");
}
}
19
Source : MqdfParams.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
private static Stream GetResource(string resourceName)
{
replacedembly replacedembly = typeof(MqdfParams).GetTypeInfo().replacedembly;
string[] names = replacedembly.GetManifestResourceNames();
foreach (var name in names)
{
if (name.Contains(resourceName))
return replacedembly.GetManifestResourceStream(name);
}
return null;
}
19
Source : ActionManager.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
internal void LoadActions(replacedembly asm)
{
Stream actionsdata;
StreamReader actionsreader;
Configuration cfg;
string name, shortname;
bool debugonly;
string[] resnames;
replacedemblyName asmname = asm.GetName();
// Find a resource named Actions.cfg
resnames = asm.GetManifestResourceNames();
foreach(string rn in resnames)
{
// Found one?
if(rn.EndsWith(ACTIONS_RESOURCE, StringComparison.InvariantCultureIgnoreCase))
{
// Get a stream from the resource
actionsdata = asm.GetManifestResourceStream(rn);
actionsreader = new StreamReader(actionsdata, Encoding.ASCII);
// Load configuration from stream
cfg = new Configuration();
cfg.InputConfiguration(actionsreader.ReadToEnd());
if(cfg.ErrorResult)
{
string errordesc = "Error in Actions configuration on line " + cfg.ErrorLine + ": " + cfg.ErrorDescription;
General.CancelAutoMapLoad();
General.ErrorLogger.Add(ErrorType.Error, "Unable to read Actions configuration from replacedembly " + Path.GetFileName(asm.Location));
Logger.WriteLogLine(errordesc);
General.ShowErrorMessage("Unable to read Actions configuration from replacedembly " + Path.GetFileName(asm.Location) + "!\n" + errordesc, MessageBoxButtons.OK);
}
else
{
// Read the categories structure
IDictionary cats = cfg.ReadSetting("categories", new Hashtable());
foreach(DictionaryEntry c in cats)
{
// Make the category if not already added
if(!categories.ContainsKey(c.Key.ToString()))
categories.Add(c.Key.ToString(), c.Value.ToString());
}
// Go for all objects in the configuration
foreach(DictionaryEntry a in cfg.Root)
{
// Get action properties
shortname = a.Key.ToString();
name = asmname.Name.ToLowerInvariant() + "_" + shortname;
debugonly = cfg.ReadSetting(a.Key + ".debugonly", false);
// Not the categories structure?
if(shortname.ToLowerInvariant() != "categories")
{
// Check if action should be included
if(General.DebugBuild || !debugonly)
{
// Create an action
CreateAction(cfg, name, shortname);
}
}
}
}
// Done with the resource
actionsreader.Dispose();
actionsdata.Dispose();
}
}
}
19
Source : Plugin.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public Stream GetResourceStream(string resourcename)
{
string[] resnames;
// Find a resource
resnames = asm.GetManifestResourceNames();
foreach(string rn in resnames)
{
// Found it?
if(rn.EndsWith(resourcename, StringComparison.InvariantCultureIgnoreCase))
{
// Get a stream from the resource
return asm.GetManifestResourceStream(rn);
}
}
// Nothing found
return null;
}
19
Source : KHPCPatchManager.cs
with Apache License 2.0
from AntonioDePau
with Apache License 2.0
from AntonioDePau
static void UpdateResources(){
string resourceName = Executingreplacedembly.GetManifestResourceNames().Single(str => str.EndsWith("resources.zip"));
using (Stream stream = Executingreplacedembly.GetManifestResourceStream(resourceName)){
ZipFile zip = ZipFile.Read(stream);
Directory.CreateDirectory("resources");
zip.ExtractSelectedEntries("*.txt", "resources", "", ExtractExistingFileAction.OverwriteSilently);
}
}
19
Source : TestBase.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
[TestInitialize]
public void InitBase()
{
_clipartPath = Path.Combine(Path.GetTempPath(), @"EPPlus clipart");
if (!Directory.Exists(_clipartPath))
{
Directory.CreateDirectory(_clipartPath);
}
if(Environment.GetEnvironmentVariable("EPPlusTestInputPath")!=null)
{
_testInputPath = Environment.GetEnvironmentVariable("EPPlusTestInputPath");
}
var asm = replacedembly.GetExecutingreplacedembly();
var validExtensions = new[]
{
".gif", ".wmf"
};
foreach (var name in asm.GetManifestResourceNames())
{
foreach (var ext in validExtensions)
{
if (name.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
{
string fileName = name.Replace("EPPlusTest.Resources.", "");
using (var stream = asm.GetManifestResourceStream(name))
using (var file = File.Create(Path.Combine(_clipartPath, fileName)))
{
stream.CopyTo(file);
}
break;
}
}
}
//_worksheetPath = Path.Combine(Path.GetTempPath(), @"EPPlus worksheets");
//if (!Directory.Exists(_worksheetPath))
//{
// Directory.CreateDirectory(_worksheetPath);
//}
var di=new DirectoryInfo(_worksheetPath);
_worksheetPath = di.FullName + "\\";
_pck = new ExcelPackage();
}
19
Source : MockConditions.cs
with MIT License
from Apps72
with MIT License
from Apps72
public void LoadTagsFromResources(replacedembly replacedembly, params string[] fileNames)
{
string[] allResources = replacedembly.GetManifestResourceNames();
foreach (var filename in fileNames)
{
string resourceName = allResources.FirstOrDefault(i => i.EndsWith($".{filename}.{MockResourceOptions.Extension}", StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(resourceName))
{
// Split the filename to "[Identifier]-[TagName]"
string[] resourceNameParts = filename.Split(new[] { MockResourceOptions.TagSeparator }, StringSplitOptions.RemoveEmptyEntries);
string tagName = resourceNameParts.Length == 2 ? resourceNameParts[1] : filename;
this.WhenTag(tagName)
.ReturnsTable(MockTable.FromFixed(replacedembly, resourceName));
}
}
}
19
Source : ApplicationBuilderExtensions.cs
with MIT License
from ardacetinkaya
with MIT License
from ardacetinkaya
public static IApplicationBuilder UseCommandLine(this IApplicationBuilder applicationBuilder, string webRootPath)
{
var component = replacedembly.GetExecutingreplacedembly();
var componentResources = component.GetManifestResourceNames();
var destinationFolderPath = Path.Combine(webRootPath, "Blazor.CommandLine");
if (!Directory.Exists(destinationFolderPath))
{
Directory.CreateDirectory(destinationFolderPath);
}
foreach (var resource in componentResources)
{
var position = resource.LastIndexOf(":");
var resourceName = resource.Substring(position + 1, resource.Length - position - 1);
using (var resourceStream = component.GetManifestResourceStream(resource))
{
if (resourceStream != null)
{
var bufferSize = 1024 * 1024;
using var fileStream = new FileStream(Path.Combine(destinationFolderPath, resourceName)
, FileMode.OpenOrCreate, FileAccess.Write);
fileStream.SetLength(resourceStream.Length);
var bytesRead = -1;
var bytes = new byte[bufferSize];
while ((bytesRead = resourceStream.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
}
}
}
return applicationBuilder;
}
19
Source : Program.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private static void PreloadResources<TResources>(ResourceManager resourceManager)
{
replacedembly replacedembly = typeof(TResources).replacedembly;
FieldInfo resourceSetsField = typeof(ResourceManager).GetField("_resourceSets", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary<string, ResourceSet> resourceSets = (Dictionary<string, ResourceSet>)resourceSetsField.GetValue(resourceManager);
foreach (string resourceName in replacedembly.GetManifestResourceNames())
{
Match match = Regex.Match(resourceName, Regex.Escape(typeof(TResources).FullName) + @"\.([-\w]+)\.resources$");
if (!match.Success)
continue;
string culture = match.Groups[1].Value;
using Stream stream = replacedembly.GetManifestResourceStream(resourceName);
ResourceSet resSet = new ResourceSet(stream);
resourceSets.Add(culture, resSet);
}
}
See More Examples