I have embedded a resource into my code, I want to read the text and apply the text to some string variables. I have worked out how to do that when I use an external file but I only want the .exe
string setting_file = "config.txt";
string complete = File.ReadAllText(setting_file);
string Filename = complete.Split('#').Last(); //"Test.zip";
string URL = complete.Split('#').First();
How can I read the resource config.txt
(Preferably without new procedures)
The File class is only used for accessing the file system whereas your file is no longer in the system so this line needs to change. As others have hinted with linked answers you need to get the stream for the resource and then read that. The below method can be called to replace your File.ReadAllText method call.
private static string GetTextResourceFile(string resourceName)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
The resourceName will be something along the lines of MyNamespace.Myfile.txt. If you are having problems finding your resourcename then the method GetManifestResourceNames on the assembly will help you identify it while debugging.
Also of note is the above method will throw an exception if the resource isn't found. This should be handled in real code but I didn't want to confuse the above sample with standard error handling code.
See also How to read embedded resource text file for a different question with the same answer (that differs in that it asks only about streams but in fact streams seem to be the only way to access embedded resource files anyway).
This is how you can use embedded files Properties.Resources.yourfilename
Related
I'm trying to read the contents of a file in a Visual Studio extension. The following code works, but forces me to open the file, if it isn't (otherwise it crashes):
textDocument = (TextDocument)projectItem.Document.Object("TextDocument");
EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string text = editPoint.GetText(textDocument.EndPoint);
I can get the path of the project, so I suppose I could make an educated guess as to the location of the project item. However, ideally I'd like to either get the file contents without opening it; or, alternatively, get the path to the project item (then I could just use System.IO to access the file contents).
I've looked, but don't seem to be able to find any mention of either of these. Can anyone point me in the right direction, please?
You can get the path from a ProjectItem by reading its properties.
var path = YourProjectItem.Properties.Item("FullPath").Value.ToString()
After you have the path you can read its content with System.IO.
string content = File.ReadAllText(path);
If the file is somewhat larger and you are getting troubles with the current code due to size, you should take a look at the StreamReader class.
I'm not sure if this is possible for extensions but you could probably use System.IO, like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
string fileText = File.ReadAllText(filePath);
You could also use StreamReader like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
using (StreamReader sr = new StreamReader(filePath))
fileText = sr.ReadToEnd();
EDIT:
I think I understand you better now.
The only way to "get the file contents without opening it" would be if the extension were to give you that data actively, but I can safely assume it doesn't.
When reading a file, you should already know where the file is (if you don't know then either you're not intended to access that file or you just haven't looked long enough).
I'd try searching the SDK files manually (Or with a file crawler).
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.
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.