Save XML file at custom location - c#

I'm a very beginner with c#.
I write a little XML converter. In the debug mode saves my xml files under bin/debug.
I use:
XmlWriter xw = XmlWriter.Create("Filename.xml")
When I compile the code and run it, the xml are not saved.
What can I do to ensure that the xml is stored at a particular path?
The save Location path comes from a form as a string

You just need to combine the path and the xml file name, then use XmlWriter to write xml element:
string pathName = Path.Combine(location, "Filename.xml"); // location is the string from your form.
using (var xw = XmlWriter.Create(pathName))
{
xw.WriteStartElement("myxml");
}

XmlWriter creates a new XmlWriter instance using the filename and XmlWriterSettings object. (Not saving the file!)
When you have the xml you can save it using System.IO:
File.WriteAllText(saveLocationPath, yourXML);

Related

Find and append to file without loading it in memory?

Im writing a simple XML file for logging that looks like this :
<root>
<objects>
</objects>
</root>
The file is created the first time like this
using (xmlWriter = new XmlTextWriter(filePathAndName, System.Text.Encoding.UTF8))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root");
xmlWriter.WriteStartElement("objects");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
Now I need to place objects(serialized data contracts in string format) within the objects tag without loading it to memory.
I have found a lot of suggestions on how to do this but all loads the entire file into memory and thats no good when the files is large.
My thought is this :
Open file with some kind of reader
Search from end of file to </objects> tag
Store the index and close the reader/file
Open the file again but this time as a writer
Write the serlized datacontract to the index(just before the
Close file
I'm however not sure how to do this properly in C#?
The solution for me in this case was XML Inclusion Technique, it is not perfect but the login is much simplier. I can use appendToFile instead of manipulate or read into memory.

How to read a local xml file into a string

In the root of my solution I have a XML file, which content I want to write to a string, because later I parse this string. What is the easiest way in WP8. I dont want to parse anything, just my string to have the content of the xml file, then I use this string the way I do now. Or the file needs to be txt with xml inside, I dont care. Thanks!
how about
using System.Xml.Linq;
// load the file using;
var xDocument = XDocument.Load(#"C:\MyFile.xml");
// convert the xml into string
string xml = xDocument.ToString();
You may want to try this :
StreamResourceInfo strm = Application.GetResourceStream(new Uri("/myProject;component/States.xml",UriKind.Relative));
StreamReader reader = new StreamReader(strm.Stream);
string xmlData = reader.ReadToEnd();
[Nokia developer community wiki: Parse Local XML file in Windows Phone]
or another possible way as shown in this other SO question : Windows Phone 8 - reading and writing in an existing txt file in the project

Loading resources from another project?

I'm trying to load an XML file from a separate project; One of these projects is a game engine, which calls the XML document reader and takes in a path specifying the relative directory to the file.
From Engine
XDocument doc;
try
{
Stream stream = this.GetType().Assembly.GetManifestResourceStream(path);
doc = XDocument.Load(stream);
}
catch
{
doc = XDocument.Load(path);
}
From the other project
string filePath = "Test.xml";
Npc npc = new Npc("somename", 2,filePath);
Test.xml resides in the other project's root directory. The Npc constructor makes a call to a Statistics object constructor, which then calls the method which loads the XDocument. As this is happening, the filePath is simply passed downward through the layers.
I've looked at this, and tried the embedded resource example, which is ultimately what I'm trying to accomplish, and it didn't work for me.
What am I doing wrong, here?
Update
I changed Text.xml to Chronos.Text.xml, as that is where the file resides. In my debugger, I see that the stream simply returns null when I use that as a path:
try
{
Stream stream = this.GetType().Assembly.GetManifestResourceStream("Chronos.Test.xml"); //returns null
doc = XDocument.Load(stream); //Exception thrown
}
catch
{
doc = XDocument.Load(path); //File not found
}
Embeded resources are embeded directly in the executable. Assembly.GetManifestResourceStream() is trying to open a stream on the embeded resource, what you should be providing is the resource name in the following format AssemblyDefaultNamespace.Directory.Filename.
If you are trying to open an XML file from another directory, you will have to provide the full path to XDocument.Load(), or a path relative from your current project output directory pointing to that other directory.
Another solution would be to copy the data from the other project into your project and specify that you want the file to be copied to your output directory.

How to write xml file using C#

I am newer person in c# asp.net .
I want to write xml file in c# code behind file in my asp.net web application and pass this xml file as a string to a webservice . Can any one able to help me its will very useful for my project .
Thank you
As "fiver" had mentioned you could use the XmlDocument or the new simplified version XDocument for creating XML Documents. Here's a sample code snippet from MSDN for creating XML documents and writing to a file.
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
This will write the following text to the xml file
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Child>content</Child>
</Root>
Note: XDocument is supported only on .NET framework 3.5 and above
You can serialize objects in Xml by using XmlSerializer class:
Serializing to a file:
void SaveAsXmlToFile(object o, string fname)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
using (var f = File.Open(fname, FileMode.OpenOrCreate))
ser.Serialize(f, o);
}
You can also use DataContractSerializer class the same way as XmlSerializer.
You can also serialize an object to a string, and return it:
Serializing to a string:
string ToXml(object o)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
ser.Serialize(sw, o);
return sb.ToString();
}
Also, if you need more control over produced Xml, you can use structured xml objects, like XmlDocument and so on, or xml writing classes like XmlWriter as denoted in other answers.
You can use the XMLDocument class. It has various CreateXXX methods for creating XML elements.
It seem you don't need to save the XML file, so you can use the Save(String) method to serialize it to a string, when you are done.
See this question:
How can I build XML in C#?
If you're using .Net4 the XDocument class would work, for .Net2 use the XmlDocument.
The XDocument.ToString() directly returns the XML as a string. For the XmlDocument class you would use the XmlDocument.Save() method, to save to a stream or a TextWriter XmlDocument.OuterXml property.
Both examples on that question demonstrate how to output it as a string. You can use that to pass the string to your web service.
using System.Xml;
using System.Xml.Schema;
XmlTextWriter xtwFeed = new XmlTextWriter(Server.MapPath("rss.xml"), Encoding.UTF8);
xtwFeed.WriteStartDocument();
// The mandatory rss tag
xtwFeed.WriteStartElement("rss");
xtwFeed.WriteAttributeString("version", "2.0");
// Write all the tags like above and end all elements
xtwFeed.WriteEndElement();
xtwFeed.WriteEndDocument();
xtwFeed.Flush();
xtwFeed.Close();

LINQ to XML - Adding a node to a .csproj file

I've written a code generator, that generates C# files. If the file being generated is new, I need to add a reference to it to our .csproj file. I have the following method that adds a node to a .csproj file.
private static void AddToProjectFile(string projectFileName, string projectFileEntry)
{
StreamReader streamReader = new StreamReader(projectFileName);
XmlTextReader xmlReader = new XmlTextReader(streamReader);
XElement element;
XNamespace nameSpace;
// Load the xml document
XDocument xmlDoc = XDocument.Load(xmlReader);
// Get the xml namespace
nameSpace = xmlDoc.Root.Name.Namespace;
// Close the reader so we can save the file back.
streamReader.Close();
// Create the new element we want to add.
element = new XElement(nameSpace + "Compile", new XAttribute("Include", projectFileEntry));
// Add the new element.
xmlDoc.Root.Elements(nameSpace + "ItemGroup").ElementAt(1).Add(element);
xmlDoc.Save(projectFileName);
}
This method works fine. However, it doesn't add the node on a new line. It will append it to the previous line in the .csproj file. This makes for a bit of a mess when doing TFS merging. How can I add the new node on a new line?
Why are you using StreamReader and then XmlTextReader? Just pass the filename to the XDocument.Load. Then everything works as you would expect.
If you create the reader on your own XDocument can't modify its settings and thus the reader will report whitespaces which are then stored in the XLinq tree and when written out they disable automatic formatting in the writer. So you can either set IgnoreWhitespaces to true on your reader, or pass the input just as a filename, which will let XDocument use its own settings which will include IgnoreWhitespaces.
As a side note, please don't use XmlTextReader, a more spec compliant XML reader is created when you call XmlReader.Create.

Categories