views:

127

answers:

6

Is there a way in Visual Studio (any version) to embed the content of a file in another file upon compiling? For instance, if one wanted to embed an xml file in a vb code file how would it best be done?

A: 

If you don't mind it actually being in your code, you can use an XML Literal.

Robert Harvey
I am using this, but I want the file separate as well as in the code.
Charles Y.
A: 

I was about to mention using the #include preprocessor directive (for C and C++), but then you mentioned VB. I don't think VB supports such a thing.

Greg Hewgill
I was hoping it did. I am used to C based languages and was looking for something like an equivalent of #include as I've used it before in C++ and php.
Charles Y.
A: 

I have no idea on how to go about doing this. But the first thought that came to my mind was that of Build Providers (the thing that generate classes from xml file in case of an ORM).

I searched & found 1 more thing called Custom Tools, which can act on a file existing in your solution and can be used to generate code file.

See if this link helps at all - http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/

shahkalpesh
+1  A: 

Have a look at Resources. You can create a string resource that has your xml. This is then compiled into your application image.

Brian beat me about the embeded resource as I was looking for the resource URL :)

Wayne
Thanks for the info, but I do specifically want to embed from a separate file.
Charles Y.
+2  A: 

Add the file to your project, right click on the file and select its properties. Under "Build Action" change it to "Embedded Resource". Now when you compile the file is automatically embedded as a resource.

Here is an example showing how to access an embedded bitmap resource.

Brian Ensink
Thanks for the answer Brian, this looks like what I want, but I can only find ways of doing it in C#, how do I do this in vb.net?
Charles Y.
I just found `Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream("<ProjectNamespace>.filename.xsd"` which returns a `System.IO.Stream` with the contents of the file.
Charles Y.
@Charles Y. You use that same class you mentioned to open the embedded resource stream regardless of whether its C# or VB.NET.
Brian Ensink
A: 

What I've done in the past is write a simple .bat file that concatenates 3 different sources into a final source file that actually gets compiled. The .bat file is run as part of the Pre-Build event.

Project

  • SourceTop.vb
  • Source.xml
  • SourceBottom.vb

All of these files have a Build Action of "None"

  • Merged.vb

merge.bat

type SourceTop.vb > Merged.vb type Source.xml >> Merged.vb type SourceBottom.vb >> Merged.vb

Paul Alexander
Thanks for the suggestion Paul. I don't think this is quite what I am looking for, but it's good to know I have it to fall back on if I can't find what I want.
Charles Y.