C# Quick Reference - Sheet 4 of 4
by Gayle Laakmann, v 1.0

XML—Reading
public void Open()
   {
   XmlTextReader f = null;
   try
   {
      f = new XmlTextReader(path);
      while (f.Read())
      {
         if (f.NodeType == XmlNodeType.Element)
         {
            if (f.LocalName.Equals("Title"))
            {
               string s = f.ReadString();
               string id = f.GetAttribute("id");
            }
         }
      }
      note.Close();
   }
   catch (Exception e)
   {
     ...
   }
   finally

XML—Writing
public void Save()
{
   XmlTextWriter f = null;
   try
   {
        f = new XmlTextWriter(m_path, null);
        f.Formatting = Formatting.Indented;
        f.Indentation= 6;
        f.Namespaces = false;
        f.WriteStartDocument();
        f.WriteStartElement("", "Note", "");
        f.WriteStartElement("", "Title", "");
        f.WriteString(this.m_title);
        f.WriteStartAttribute("","id","");
        f.WriteString(v.ToString());
        f.WriteEndAttribute();
        f.WriteEndElement();
        f.WriteEndElement();
        f.Flush();
   }
   catch(Exception e)
   {
      ...
   }
   finally
   {
      if (f != null)
      {
        f.Close();
      }
   }
}

File IO—Reading
if (File.Exists(path))
{
System.IO.StreamReader file = null;
try
   {
      file = new StreamReader(path);
      string data = file.ReadToEnd();
      file.Close();
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.ToString());
   }
   finally
   {
      if (file != null)
      {
         file.Close();
      }
   }
}

File IO—Writing
StreamWriter f = new StreamWriter(pth, false);
try
{
   f.WriteLine("stuff to write to file");
}
catch (Exception ex)
{
   MessageBox.Show(ex.ToString());
}
finally
{
   if (f != null)
   {
      f.Close();
   }
}

Registry—Reading
//using Microsoft.Win32
RegistryKey regKey = Registry.LocalMachine;
Key.CreateSubKey("Software\\Glaak\\Fetcha");
object o = regKey.GetValue("lastUser");
if ((o != null) && (o is string))
{
   string name = (string) o;
}

Registry—Writing
// using Microsoft.Win32
RegistryKey regKey = Registry.LocalMachine;
regKey.CreateSubKey("Software\\Glaak\\Fetcha");
regKey.SetValue("lastUser", username);
regKey.Close();
Copyright © Harbor Mist, LLC 2005.  All rights reserved.

Visitors:  Hit Counter