Well In my C# project I add a .xml file to the resources, I want it to be extracted/copied from it to the application path, I was trying to doing this:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);//Declaration of the apppath
File.Copy(appPath, Properties.Resources.config);//process for copy
But is not working :/, how can I do what I want?
Make sure the build action on your resource is set to "embed resource".
var assembly = Assembly.GetExecutingAssembly();
// See what resources are in the assembly (remove from the final code)
foreach (var name in assembly.GetManifestResourceNames()) {
Console.Writeline("'{0}'", name);
}
using (var inputStream = assembly.GetManifestResourceStream(resourcePath)) {
using( var outStream = File.OpenWrite(copyToPath)) {
input.CopyTo(outStream);
}
}
Related
How do I extract just the file name excluding the namespace using the following code? Currently this code includes the entire namespace from GetManifestResourceNames().
Assembly assembly = System.Reflection.Assembly.LoadFile(resourceLocation + #"\\" + file);
string[] names = assembly.GetManifestResourceNames();
foreach (var name in names.Where(x => x.EndsWith("xsd")).ToList())
{
using (System.IO.Stream stream = assembly.GetManifestResourceStream(name))
{
using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(outputDir, name), System.IO.FileMode.Create))
You can use GetManifestResourceInfo to get additional information, such as the file name.
Taking your example, you might end up with something like the following:
string[] names = assembly.GetManifestResourceNames();
foreach (var name in names.Where(x => x.EndsWith("xsd")).ToList())
{
var info = assembly.GetManifestResourceInfo(name);
if (info != null)
{
var fileName = info.FileName;
// Do your stuff that needs filename here.
}
}
EDIT: This SO post might be relevant, if you find GetManifestResourceInfo returning null in these cases: Why does GetManifestResourceStream returns null while the resource name exists when calling GetManifestResourceNames?
The resources should be set to build action of "Embedded Resource", and there is the code security gotcha that is mentioned here: http://adrianmejia.com/blog/2011/07/18/cs-getmanifestresourcestream-gotcha/
I have a c# program generating some WebPages. In my project I have added some JavaScript files to the project via the ResourceManager.
Now I want to get all the ResourceNames and save them to my Destination path.
I know this question have been asked a million times in here but I can not get it to work.
Here I try to list all my resources
foreach (var res in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
....
}
But I do not get the Resource names in res but
"WindowsFormsApplication3.Form1.resources" the first time in the loop
and "WindowsFormsApplication3.Properties.Resources.resources" second time
and "WindowsFormsApplication3.Properties.Resources.Designer.cs" third time
What am I doing wrong?
You are just getting the names of the manifest resources, which is not the same thing as Resource file (resx) resources.
To get the resource file resources from a manifest resource file name like "WindowsFormsApplication3.Properties.Resources.resources" you would have to do:
foreach (var manifestResourceName in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName))
{
if (stream != null)
{
using (var rr = new ResourceReader(stream))
{
foreach (DictionaryEntry resource in rr)
{
var name = resource.Key.ToString();
string resourceType;
byte[] dataBytes;
rr.GetResourceData(name, out resourceType, out dataBytes);
}
}
}
}
}
And then you can save the bytes wherever you want.
Is it possible to list all files which was added to assembly and marked as a resource (not embedded).
I've tried GetManifestResourceNames method. It only works with embedded resources. But I need to be that files marked as a resource, in order to access that files by using uri like this pack://application:,,,/ApplicationName;component/Resources/logo.png
thanks
You can access it like this:
var image = new BitmapImage(new Uri("pack://application:,,,/ApplicationName;component/Resources/logo.png", UriKind.Absolute))
[EDIT]
And you can list all of them by calling this method:
public static string[] GetResourceNames()
{
var asm = Assembly.GetEntryAssembly();
string resName = asm.GetName().Name + ".g.resources";
using (var stream = asm.GetManifestResourceStream(resName))
using (var reader = new System.Resources.ResourceReader(stream))
{
return reader.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
}
}
I have some bitmaps in a sub-folder of resource folder (say, Resource/Bitmap) and I want to load them into a bitmap[] at one time, that is,
BitmapSource[] bitmaps=
TheMethodIWantToImplement(
new Uri("pack://application:,,,/MyAssembly;component/Resources/Bitmap",
UriKind.Absolute));
But I found that Directory.GetFiles does not accept an Uri argument. So...What should I do? Thank you.
Thank you, #Teudimundo. I modified the snippet of that link as follows:
var asm = Assembly.GetEntryAssembly();
string resName = asm.GetName().Name + ".g.resources";
using (var stream = asm.GetManifestResourceStream(resName))
using (var reader = new System.Resources.ResourceReader(stream))
{
var paths = from entry in reader.Cast<DictionaryEntry>()
where ((string)entry.Key).Contains("sub-folder-name")
select entry.Key;
if (paths.Any())
{
foreach (string path in paths)
{
Uri uri = new Uri(String.Format(
"pack://application:,,,/{0};component{1}", asm.GetName(), path)
, UriKind.Absolute);
//use the uri for the rest
}
}
}
But I still want to use the resource stream directly (can be retrieved via select entry.Value in the LINQ expression above), which is an instance of UnmanagedMemoryStream. I need MemoryStream to construct my object but I found no elegant methods for conversion.
How do I embed an external executable inside my C# Windows Forms application?
Edit: I need to embed it because it's an external free console application (made in C++) from which I read the output values to use in my program. It would be nice and more professional to have it embedded.
Second reason is a requirement to embed a Flash projector file inside a .NET application.
Simplest way, leading on from what Will said:
Add the .exe using Resources.resx
Code this:
string path = Path.Combine(Path.GetTempPath(), "tempfile.exe");
File.WriteAllBytes(path, MyNamespace.Properties.Resources.MyExecutable);
Process.Start(path);
Here is some sample code that would roughly accomplish this, minus error checking of any sort. Also, please make sure that the license of the program to be embedded allows this sort of use.
// extracts [resource] into the the file specified by [path]
void ExtractResource( string resource, string path )
{
Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
byte[] bytes = new byte[(int)stream.Length];
stream.Read( bytes, 0, bytes.Length );
File.WriteAllBytes( path, bytes );
}
string exePath = "c:\temp\embedded.exe";
ExtractResource( "myProj.embedded.exe", exePath );
// run the exe...
File.Delete( exePath );
The only tricky part is getting the right value for the first argument to ExtractResource. It should have the form "namespace.name", where namespace is the default namespace for your project (find this under Project | Properties | Application | Default namespace). The second part is the name of the file, which you'll need to include in your project (make sure to set the build option to "Embedded Resource"). If you put the file under a directory, e.g. Resources, then that name becomes part of the resource name (e.g. "myProj.Resources.Embedded.exe"). If you're having trouble, try opening your compiled binary in Reflector and look in the Resources folder. The names listed here are the names that you would pass to GetManifestResourceStream.
Just add it to your project and set the build option to "Embedded Resource"
This is probably the simplest:
byte[] exeBytes = Properties.Resources.myApp;
string exeToRun = Path.Combine(Path.GetTempPath(), "myApp.exe");
using (FileStream exeFile = new FileStream(exeToRun, FileMode.CreateNew))
exeFile.Write(exeBytes, 0, exeBytes.Length);
Process.Start(exeToRun);
Is the executable a managed assembly? If so you can use ILMerge to merge that assembly with yours.
Here's my version:
Add the file to the project as an existing item, change the properties on the file to "Embedded resource"
To dynamically extract the file to a given location: (this example doesn't test location for write permissions etc)
/// <summary>
/// Extract Embedded resource files to a given path
/// </summary>
/// <param name="embeddedFileName">Name of the embedded resource file</param>
/// <param name="destinationPath">Path and file to export resource to</param>
public static void extractResource(String embeddedFileName, String destinationPath)
{
Assembly currentAssembly = Assembly.GetExecutingAssembly();
string[] arrResources = currentAssembly.GetManifestResourceNames();
foreach (string resourceName in arrResources)
if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
{
Stream resourceToSave = currentAssembly.GetManifestResourceStream(resourceName);
var output = File.OpenWrite(destinationPath);
resourceToSave.CopyTo(output);
resourceToSave.Close();
}
}
Add File to VS Project
Mark as "Embedded Resource" -> File properties
Use name to resolve: [Assembly Name].[Name of embedded resource] like "MyFunkyNTServcice.SelfDelete.bat"
Your code has resource bug (file handle not freed!), please correct to:
public static void extractResource(String embeddedFileName, String destinationPath)
{
var currentAssembly = Assembly.GetExecutingAssembly();
var arrResources = currentAssembly.GetManifestResourceNames();
foreach (var resourceName in arrResources)
{
if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
{
using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
{
using (var output = File.OpenWrite(destinationPath))
resourceToSave.CopyTo(output);
resourceToSave.Close();
}
}
}
}
Extract something as string, if needed:
public static string ExtractResourceAsString(String embeddedFileName)
{
var currentAssembly = Assembly.GetExecutingAssembly();
var arrResources = currentAssembly.GetManifestResourceNames();
foreach (var resourceName in arrResources)
{
if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
{
using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
{
using (var output = new MemoryStream())
{
resourceToSave.CopyTo(output);
return Encoding.ASCII.GetString(output.ToArray());
}
}
}
}
return string.Empty;
}