I can't read my embedded XML file from my second C# project
You've to refer to Windows Service project Assembly
to make it work
The problem with your code is This.GetType().Assesmbly
gives current Assembly
In your case WPF Assembly
and obviously you'll not find what you need there.
Try this
Assembly windowsServiceAssembly = typeof(SomeTypeFromThatAssembly).Assembly;
string[] names = windowsServiceAssembly.GetManifestResourceNames();
Hope this helps.
How to read embedded resource text file
You can use the Assembly.GetManifestResourceStream
Method:
Add the following usings
using System.IO;
using System.Reflection;Set property of relevant file:
ParameterBuild Action
with valueEmbedded Resource
Use the following code
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}resourceName
is the name of one of the resources embedded inassembly
.
For example, if you embed a text file named"MyFile.txt"
that is placed in the root of a project with default namespace"MyCompany.MyProduct"
, thenresourceName
is"MyCompany.MyProduct.MyFile.txt"
.
You can get a list of all resources in an assembly using theAssembly.GetManifestResourceNames
Method.
A no brainer astute to get the resourceName
from the file name only (by pass the namespace stuff):
string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("YourFileName.txt"));
A complete example:
public string ReadResource(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
or as an async extension method:
internal static class AssemblyExtensions
{
public static async Task<string> ReadResourceAsync(this Assembly assembly, string name)
{
// Determine path
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using Stream stream = assembly.GetManifestResourceStream(resourcePath)!;
using StreamReader reader = new(stream);
return await reader.ReadToEndAsync();
}
}
// Usage
string resourceText = await Assembly.GetExecutingAssembly().ReadResourceAsync("myResourceName");
How to load an XML file from a file in the solution, build with Embedded Resource?
Use GetManifestResourceStream()
:
var asm = Assembly.GetExecutingAssembly();
using(var stream = asm.GetManifestResourceStream("Namespace.Champions.xml"))
{
// ...
}
The exact names used to reference resources can be found by calling GetManifestResourceNames()
.
how to embed an xml file to a resource file
If you add the XML file to a Visual Studio project and, in the Property window for it, select Build Action: Embedded resource, the file will be embedded into the build output artifact for that project.
To access it from code, use something like:
string resourceName = "Namespace.Prefix.FileName.xml";
Assembly someAssembly = LoadYourAssemblyContainingTheResource();
XmlDocument xml = new XmlDocument();
using (Stream resourceStream = someAssembly.GetManifestResourceStream(resourceName))
{
xml.Load(resourceStream);
}
// The embedded XML resource is now available in: xml
If the resource you're loading is embedded in your own assembly, you can do something like Assembly.GetExecutingAssembly()
to achieve what I listed as LoadYourAssemblyContainingTheResource()
above, or possibly typeof(SomeTypeInYourResourceAssembly).Assembly
It's unclear what you mean by "want to modify the contents" - you cannot modify the resource inside the assembly at run-time, but whenever you change the XML file and recompile, the new version will be embedded.
How can I retrieve an embedded xml resource?
The MSDN page for GetManifestResourceStream makes this note:
This method returns a null reference
(Nothing in Visual Basic) if a private
resource in another assembly is
accessed and the caller does not have
ReflectionPermission with the
ReflectionPermissionFlag.MemberAccess
flag.
Have you marked the resource as "public" in your assembly?
How to query an embedded XML file using LINQ?
Open the embedded resource as a stream:
XElement doc;
using (var stream = typeof(SomeTypeInTheAssembly).Assembly
.GetManifestResourceStream("MyXML.xml"))
{
doc = XElement.Load(stream);
}
There's no need to go via an intermediate string representation.
Related Topics
Why Does Timespan.Parseexact Not Work
Convert from Scientific Notation String to Float in C#
Replace Unicode Escape Sequences in a String
Is There a Task Based Replacement for System.Threading.Timer
How to Remove New Line Characters from a String
Getting Hash of a List of Strings Regardless of Order
.Include() VS .Load() Performance in Entityframework
Cannot Implicitly Convert Type 'Int' to 'T'
How to See What My Reactive Extensions Query Is Doing
Click Through Transparency for Visual C# Window Forms
What Does This C# Code with an "Arrow" Mean and How Is It Called
Revisiting Task.Configureawait(Continueoncapturedcontext: False)
Get Individual Query Parameters from Uri
Invoke Notifyicon's Context Menu
Measure a String Without Using a Graphics Object
How to Get User Type C# Syntax Highlighting Working Again in VS 2012 Rc