Reputation: 1327
I have an *.xml file that I have added to my solution and set it's build action to "Resource". I want to load its contents into a List<string>
.
I found out I can access the file with ResourceManager
(after numerous tries I concluded it's impossible to access it in another way).
But XDocument.Load
requires an Uri, which I have no idea what it is for my file, because it doesn't work with what I've read on other questions and MSDN.
Here is a picture of my solution structure, pertaining to the file:
(I need "ServerList.xml")
I tried using the following Uris:
None of them work.
This code, does, somewhat:
var rm = new ResourceManager("SQLExecutor.g", Assembly.GetExecutingAssembly());
var rset = rm.GetResourceSet(CultureInfo.InvariantCulture, true, true);
var obj = SerializeToStream rset.GetObject(@"data/serverlist.xml", true);
So, now, obj
is an object but I need either an Uri or a Stream to pass to XDocument.Load
. I actually just need to get the information out of the *.xml and am only using XDocument, because I think it would be best, but am having problems serializing obj
.
So what, exactly, should I do in order to be able to load this "ServerList.xml" file in an XDocument, so I can work with it?
Upvotes: 1
Views: 322
Reputation: 4475
Check the link https://stackoverflow.com/a/18680852/7974050, if that suits your purpose.
Alternatively, you can
Set the file Build Action to Embedded Resource. Suppose, xml file is in root directory of your application. Now, when you build your solution, it will get embedded in the dll.
You can get this data in
XmlReader reader = XmlReader.Create(new StringReader(GetResourceTextFile("postdata.xml")));
and then load this reader in XDocument.
public string GetResourceTextFile(string filename)
{
string result = string.Empty;
// In the code below, replace xyz. with the name of your dll + .
// (dot). Idea is to treat file like dllName.filename.xml
using (Stream stream = this.GetType().Assembly.
GetManifestResourceStream("xyz." + filename))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Upvotes: 2