Confused about embedded resources - c#

I have a class library that contains some generic proceesing functionality - call it "Engine".
I include the class library in a number of web applications.
The engine library needs an XML file as input, but the content is unique to each project.
At the moment I manually copy the XML file into each project. The engine always looks for a file in the application route.
However, I've gotten a little confused with regards to embedded resources. In order to validate the XML, I've created an XSD in my engine project and set the Build Action to EmbeddedResource.
I can't see the difference between setting the BuildAction to Content and EmbeddedResource in this case, which has led me to doubt the way that things are currently set up.
I've not a lot of experience at this level, so need some guidance. Any advice would be appreciated.

EmbeddedResource means that the xsd is embedded inside the assembly during build, while Content means it is just copied along to the output folder. You want the embedded resource thing it sounds like.
You can access Embedded resources through code like this:
string resourceName = "SomeNameSpace.SomeFile.xsd";
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
if ( stream == null )
throw new ArgumentException("resource not found", "resourceName");
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
return result;
}
}

Related

Creating embedded resource in C# class library if it doesn't exist

I have an issue with a class library; I am preparing a library with an interface that represents a specific data storage signature. The purpose is to use the interface as a basis for implementing a number of specific classes storing configuration information in different formats (text files, xml files, etc.) while retaining the same usage profile to the application using it. I have a problem, though. In this case I am trying to embed an xml file as a resource - this file is one type of format to store configuration data. The file is located as an embedded resource in a subfolder to the project, as shown in the attached illustration.
In the following code snippet it is shown how I have implemented the functionality until now.
public ConfigInfoXmlSource()
{
if (!string.IsNullOrEmpty(Settings.Default.CurrentConfigFile))
FileNameAndPath = Settings.Default.CurrentConfigFile;
else
FileNameAndPath = DefaultConfigFileName + DefaultFileExtension;
// Prepare XML.
System.Reflection.Assembly a = Assembly.GetExecutingAssembly();
XmlDocument doc = new XmlDocument();
Stream manifestResourceStream =
a.GetManifestResourceStream("TestTool.Config.Config1.xml");
if (manifestResourceStream == null)
{
// ???
}
...
doc.Load(manifestResourceStream);
...
}
In the section marked "Prepare XML" I am trying to read a stream from the embedded resource. After the reading, it is tested whether a stream was indeed created. If the file is found, the manifestResourceStream will contain the xml data - so far so good. The problem arises if the file for some reason has been accidentally deleted - in that case I want to create a new file as an embedded resource to replace the deleted file. That is supposed to happen in the conditional in the part shown as "???".
I have tried everything I could think of, searched Google for answers, etc. - to no avail.
Does anyone have a clue to how this is accomplished? Any help will be greatly appreciated.
Thanks in advance.
Best regards.
If you have a embedded resource,it is built into your binaries.It is not an physical file,rather something which is present inside the built file(dll in this case).So,once it is included,I do not think it can ever be deleted. As per my knowledge embedded resource can only be set while building your project binaries and you can not explicitly do it at runtime as it is not needed due to reasons mentioned above.

How can I set up a List to be loaded each time in C# Winform?

I have a .txt file that i process into a List in my program.
I would like to somehow save that List and include it in the program itself so that it loads every time the program starts, so I don't have to process it every time from a .txt file.
Its more complicated than just "int x = 3;" cause it has like 10k lines and I don't wanna copy paste all that in the beginning.
I've looked all over but haven't found anything similar, any ideas guys?
Also if thee's a solution, can it work with any type (arrays, Dictionaries)?
As requested, the code is:
var text = System.IO.File.ReadAllText(#"C:\Users\jazz7\Desktop\links_zg.txt");
EDIT
Joe suggested the solution:
Included the file within the project, set its "build action" to embedded resource in Properties and used this code:
private string linkovi = "";
...
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "WindowsFormsApplication4.links_zg.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
linkovi = reader.ReadToEnd();
}
string linkovi now contains the txt file and is now within the application. Thanks all!
You could store the file as a resource in your executable file.
This KB article describes how to do it.
Fundamentally, youve got to choose between storing your data in memory or storing it on the hard drive. The former will cut your loading time, but might use an unacceptable amount of memory, whilst the latter is slower, as youve identified. Either way, your data has to be stored somewhere.
Do you need to load all of the data at once? If the loading time is the issue, you could process the file line by line. While this would be slower overall, you would still have access to some usable data sooner.

XML file accessible from XAML and code behind

Is it possible to have an XML file embedded in the project that can be accessed from code behind and directly from XAML using XMLDataProvider?
When I set the XML file as "Embedded Resource", I can access it from code, but not from XAML.
When I set the XML file as "Resource", I can access it from XAML, but not from code.
Now it is possible to load a Resource from using a Pack Uri from code, however the xml file is in a 'service' library and I don't feel like referencing PresentationFramework, WindowBase, etc. to make this work.
External XML file is also not an option since a lot of unit tests will break. The solution would be to add an attribute to those tests, only there are A LOT.
Any suggestions?
You can easily set xml files are Resource and then read them in code as follows
Uri uri = new Uri("/file.xml", UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(uri);
if (info != null)
{
using (StreamReader reader = new StreamReader(info.Stream))
{
string xml = reader.ReadToEnd();
}
}
Here file.xml is Resource so replace to whatever name you have

Windows Phone epub reader

I'm trying to build a wp7 application that must allow user to read ebooks in epub format. Since there isn't any available library to read epub file on a windows phone, I'm trying to create one. So I must unzip the file and then parse it.
The problem is that I can't unzip the epub file. I'm using SharpZipLib.WindowsPhone7.dll but I get an exception:
Attempt to access the method failed: System.IO.File.OpenRead(System.String)
on this line:
ZipInputStream s = new ZipInputStream(File.OpenRead(path_epubfile));
Can any one help me, please?
It's going to depend on how the content is obtained. There's three possible options here;
Option 1: If the content is added to your project with a Build Action of "Content" you can obtain a stream by using the StreamResourceInfo class (In the System.Windows.Resources namespace)
StreamResourceInfo info = Application.GetResourceStream(new Uri("MyContent.txt", UriKind.Relative));
using (info.Stream) {
// Make use of the stream as you will
}
Option 2: If you've added it to your project and set the Build Action to "Embedded Resource" then you'll need to use GetManifestResourceStream()
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ProjectName.MyContent.txt")) {
// Make use of stream as you will
}
Note: You'll need to replace "ProjectName" with the name of your project. So if your project was "EPubReader" and the embedded resource was "Example.txt" you'd need to pass "EPubReader.Example.txt" to GetManifestResourceStream(). You can use GetManifestResourceNames() to see what resources are available.
Option 3: If you've obtained the content at run time, it'll be stored in IsolatedStorage.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
using (IsolatedStorageFileStream stream = store.OpenFile("MyContent.txt", FileMode.Open)) {
// Make use of stream as you will
}
}

C# XNA - Read .txt file and create 2D array

I'm trying to create a 2D array in XNA which I'll be using as a tile map for a game I'm working on. I've read various solutions but none of them seem to be working for me. One of the main issues I'm having is an error:
Cannot autodetect which importer to use for "map.txt". There are no importers which handle this file type. Specify the importer that handles this file type in your project.
This appears to be caused by the StreamReader class that I'm attempting to use.
I'm using XNA 4.0.
My .txt file looks like this (example):
0,0,0,0,0
0,0,0,0,0
0,0,1,0,0
0,1,1,1,0
1,1,1,1,1
My C# and XNA looks like this:
string line = string.Empty;
using (StreamReader sr = new StreamReader("5x5-map"))
{
while ((line = sr.ReadLine()) != null)
{
//reads line by line until eof
//do whatever you want with the text
}
}
If anyone could help me, or point me in the direction of a working example that would be great.
Change the build action to "None" in the properties window for that file, if you're manually reading it with StreamReader. The message comes from the content pipeline trying to import it for you.
Specify the importer that handles this file type in your project.
Find the file in your content project, open the properties menu, and select an importer.
According to MSDN: Verifying the Content Importer

Categories

Resources