Assembly.GetExecutingAssembly().GetManifestResourceStream does not load stream - c#

I use stream reader to read sql data. Although resourceName is correct and the resource Build Action property is Embedded Resource it still throws following error on StreamReader:
System.ArgumentNullException: Value cannot be null.
var namespace1 = typeof(Toolbox).Namespace;
var name1 = name.Replace('\\', '.');
string resourceName = $"{typeof(Toolbox).Namespace}.{name1}";
//Innosys.Ap.GetCurrentTimeKey.sql
using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)
)
{
using (StreamReader streamReader = new StreamReader(manifestResourceStream))
return streamReader.ReadToEnd();
}
Following are my debugging results so far.
namespace1 returns the correct name space used for the class from the project i.e. The class from which I call streamReader, resource file.
name1 returns resource file name with extension. ie. myquery.sql
resourcename which basically combines the path and the file name returns from my point of view the correct resouce address. i.e. myNamespace.myquery.sql

Related

How can I stream simple text file using

I'm trying to read a simple text file using reflection just as a learning case. I'm not getting an error, but I'm also not getting the desired result of "hello world". The variable stream is coming back null.
string output = "";
var asm = Assembly.GetExecutingAssembly();
using (var stream = asm.GetManifestResourceStream("ConsoleApp1.data1.txt"))
{
if (stream != null)
{
var reader = new StreamReader(stream);
output = reader.ReadToEnd();
Console.WriteLine(output);
}
}
You're reading from a manifest resource, which means the text file needs to be embedded in the dll. Right click on the file and choose Properties, then set the Build Action to "Embedded Resource".

Embedded .Json file cannot be located after I renamed the project

I changed the name of my project and when I run it it runs fine but when it reaches the part where it does validation from json I get the following error:
Cannot find embedded resource: hot.json
but when I change the name back to the original name the error goes away. I have tried deleting the old one and then added another json file with different name and I still got the same error.
here is where the error is occurring in my code:
var assembly = Assembly.GetExecutingAssembly();
using (
var stream =
assembly.GetManifestResourceStream(
$"HotStuff.TestResources.Languages.{language}.json"))
{
if (stream == null)
throw new InvalidOperationException($"Cannot find embedded resource: {language}.json");
using (var reader = new StreamReader(stream))
{
var json = JObject.Parse(reader.ReadToEnd()).ToObject<JToken>();
var value = json.SelectToken(key.Replace(" ", "-"));
return value?.ToString() ?? string.Empty;
}
}

How can I write data to the App_Data folder in ASP.NET MVC?

I can write data to the App_Data folder in my ASP.NET Web API app like so:
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
var htmlStr = // method that returns html as a string
string htmlFilename = "platypus.html";
string fullPath = Path.Combine(appDataFolder, htmlFilename);
File.WriteAllText(fullPath, htmlStr);
I want to do something similar in an ASP.NET MVC app (the data is different - a PDF file instead of an html file), but "File" is not recognized. I try this:
using (var ms = new MemoryStream())
. . .
var bytes = ms.ToArray();
string appDataFolder = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
string pdfFilename = "test.pdf";
string fullPath = Path.Combine(appDataFolder, pdfFilename);
File.WriteAllText(fullPath, bytes);
...but get, "'System.Web.Mvc.Controller.File(byte[], string)' is a 'method', which is not valid in the given context'"
In the first place, I don't think my code is what the err msg seems to indicate it is, but nevertheless it's not accepted, so: how can I write data to the App_Data folder in ASP.NET MVC?
It looks like a namespace collision. The compiler is grabbing File from a different namespace than is expected. The File class that should make this work is in the System.IO namespace and not the System.Web.Mvc.Controller namespace.
This can be fixed by explicitly specifying the correct namespace when calling File.WriteAllText():
System.IO.File.WriteAllText(fullPath, bytes);

How to get project namespace name using Assembly.GetExecutingAssembly().GetName().Name

I am creating class library file. In this I embedded stored procedure script file. so I need to take sp data as a string and I have to create in c#. so for this GetManifestResourceStream method need full-name of assemble and script file. so I did . But I did not figure out why my stream object getting null value.
string strNameSpace = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
using (Stream stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(strNameSpace + "GP_SOP_AdjustTax.sql"))
{
// Here stream is null.
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}
}
It is sort of strange to get constant string value by getting assembly name... But you are missing "." in the way to construct the name:
Assembly.GetExecutingAssembly()
.GetManifestResourceStream(strNameSpace + ".GP_SOP_AdjustTax.sql"))
It will likely be safe and easier to simply hardcode the name:
Assembly.GetExecutingAssembly()
.GetManifestResourceStream("WhateverYoourNamespaceIs.GP_SOP_AdjustTax.sql"))
Note "How to embed and access resources" is available on Micorsoft support site and covers this topic.

Value cannot be null.Parameter name: stream error while reading the contents of embeddded file

I am doing an application in c#.
I get the error:
Value cannot be null. Parameter name: stream while reading the contentxs of embedded file
in the code
Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);
How to solve this error?
What I found is as once I faced this problem after adding a text file or template file to read the email body and than reading the path to that template file using
below syntax:
Assembly asm = Assembly.GetExecutingAssembly();
string assemblyName = asm.GetName().Name;
string emailTemplateName = xyz.tt;
emailTemplateName = assemblyName + "." + emailTemplateName;
using (StreamReader reader = new StreamReader(asm.GetManifestResourceStream(emailTemplateName)))
{
body = reader.ReadToEnd();
}
The file by default gets added to project library with property "Build Action"= Content. I changed value from "Content" to "Embedded Resource" and everything worked good.
The prefix to embedded resources is not the assembly name, but rather: the default namespace specified on the project. Your best tactic, though, is to look at:
string[] names = Asm.GetManifestResourceNames();
foreach(var name in names) Debug.WriteLine(name);
and see what the names actually are, and tweak the prefix accordingly. You will get null if it is not a complete match.

Categories

Resources