I've added a test.zip to a C# project by creating a Resource1.resx and dragged to the resx tab. It is now visible in the Solution Explorer as a child of Resources.
When the program runs, I'd like to move it from the .exe to a location on the computer like My Documents.
I've a feeling I need to convert the resource to a memory stream before I can write it to file but I'm not sure how to access the file as resource or how to convert it.
I think the following extracts the resource object (then again, it doesn't error no matter what the first param is) but I'm not sure how to proceed:
var resource = new ResourceManager("test", Assembly.GetExecutingAssembly());
Since you activate the resources you have already a ResourceManager.Just use GetObject method,get the bytes of your file and write the them to a new file with File.WriteAllBytes:
var bytes = Properties.Resources.ResourceManager.GetObject("resourceName") as byte[];
File.WriteAllBytes("newFile.zip", bytes);
You should use Assembly.GetManifestResourceStream.
using (Stream x = Assembly.GetExecutingAssembly().GetManifestResourceStream("test"))
{
...
}
Reference to MSDN.
Related
I'm new to Windows Phone development and I'm trying to do a simple training app.
I want my app to load some audio files that I've put into a folder inside the project.
Here's a short snippet:
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = Application.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
My folder structure is something like
- Project
- Kits
- TestKit_128
- Bass_126.wav
and calling
Button.setSound("Kits\\TestKit_128\\bass_126.wav");
throws a System.NullReferenceException because the path is not found when the URI is created. (At least I think so!)
What should I do?
Is there any way to load files from a folder in the project or to copy them into the IsolatedStorage when I run the app for the first time?
Thanks
EDIT:
I've just opened the XAP file with WinRar and there's no "Kits" folder so I guess that my problem is how to make it add the folder to the XAP file.
I think you have to add the folder and the file to your project (i assume you are using Visual Studio). Try rightclick on your solution and add an existing object (in this case your wav file).
Did you set the build action of the wav file to "Content"? Right click on the WAV file --> properties --> build action == content.
Try this:
Uri uri = new Uri("Kits/TestKit_128/bass_126.wav", UriKind.Relative);//Above the Kits folder only the project itself.
StreamResourceInfo sr = Application.GetResourceStream(uri);
try
{
using (Stream stream = sr.Stream)
{
//working here with your data image or wav or whatever you want from URI
}
}
catch (Exception)
{
}
This is for resource inside project and working good for me. Also prevoius note about "Content" is right, it wouldn't work without it. I think the problem is double-slashes in address.
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.
I am trying to open a resx file that is a resource in my C# project. I need to create a ResXResourceSet object. However at runtime an "Illegal characters in path" exception is thrown. This is the code I am trying to use.
var resX = new ResXResourceSet(Project.Properties.Resources.ResXFile);
The ResXResourceSet class has only two constructors (from stream and from file name). How can I create an object of the ResXResourceSet class in this situation?
Use Project.Properties.Resources.ResourceManager.GetStream("ResXFile");
If I understand correctly, the value in ResXFile is a string with the complete contents of the ResX, and not a file path, which is what ResXResourceSet expects when you pass it a string. You'll need to wrap a stream around it.
See this question for getting a stream from a string: how to generate a stream from a string?
Also, if you make the resource file into a project item, like the main resources, you can access its ResourceSet through its ResourceManager: ResXFile.ResourceManager.GetResourceSet()
You can add a ResX to your project by rightclicking on the project > Add > New Item > Resources File.
I use to store document/file in byte[] in database, and I want user can view/run that file from my application.
You need to know the file extension for the file you're writing, so the OS can run the default program based on the extension. The code would be something like this:
byte[] bytes = GetYourBytesFromDataBase();
string extension = GetYourFileExtension(); //.doc for example
string path = Path.GetTempFileName() + extension;
try
{
using(BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
writer.Write(yourBytes);
}
// open it with default application based in the
// file extension
Process p = System.Diagnostics.Process.Start(path);
p.Wait();
}
finally
{
//clean the tmp file
File.Delete(path);
}
You will need to store the file extension in the database too. If you don't have the file extension the problem becomes very difficult as you cannot rely on the operating system to work out which program to launch to handle the file.
You can use the following pattern:
Load data from database and save to file using the original file extension.
Start a new System.Diagnostics.Process that points to the saved file path.
As you have saved the file with the original file extension, the OS will look for a program that is registered for the extension to open the file.
As chibacity and Daniel suggest, storing the file extension in the db, and agreed -- storing the file extension, or at least some indicator that tells you the file type, is a good idea.
If these files are of a format of your own creation then you might also want to store information about which version of the file format the data is stored in. During development file formats are prone to changing, and if you don't remember which version you used to store the data then you have a hard job recovering the information.
The same problems are faced in object persistence generally.
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.