Tuesday, February 23, 2010

Reading Contents of a File into a String Variable

We have a file (txt,doc,xml,xslt etc tested) and we wanted to read the content of that file into a string variable.

To do this I have following code section:
=-=-=-=-=-=-=-=-=-=-=-=-=-=
using System.IO;

public string GetContentsOfFile(string URL)
{
if(string.Equals(URL,string.Empty))
throw new ArgumentNullException("URL not given");
StreamReader sr = new StreamReader(URL);
string retStr = string.Empty;
retStr = sr.ReadToEnd();
return retStr;
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=
This method will take URL of file as parameter and return a string with the contents of that file.

Enjoy...

Adding New Node to an Existing XML file

We have an XML file named: TestXML.xml

Structure is as follow:




We wanted to add a new node.

This code block will do the same

public void AddXMLNode(string XMLFilePath,string TitleToAdd, string ArtistToAdd)
{
XmlDocument doc = new XmlDocument();
doc.Load(XMLFilePath);
XmlNode node = doc.CreateNode(XmlNodeType.Element, "CD", null);
XmlNode TitleNode = doc.CreateElement("title");
TitleNode.InnerText = TitleToAdd;
XmlNode ArtistNode = doc.CreateElement("artist");
ArtistNode.InnerText = ArtistToAdd;
node.AppendChild(TitleNode);
node.AppendChild(ArtistNode);
XmlNodeList list = doc.GetElementsByTagName("Catalog");
list[0].AppendChild(node);
doc.Save(XMLFilePath);
}

Now Test This Code:

AddXMLNode(TestXML.xml,”Deewana”,”Sonu Nigam”);

Now the Structure Will Look Like:



Enjoy...