[C#] Formatierte XML-Ausgabe

/// <summary->
/// formatiert XML code
/// </summary->
/// <param name=&quot;xml&quot;->input string mit XML-code</param->
/// <param name=&quot;indentation&quot;->Anzahl Zeichen für die Einrückung</param->
/// <param name=&quot;indentchar&quot;->Einrückungszeichen</param->
/// <returns->formatierter XML-code</returns->
public string FormatXML(string xml, int indentation, char indentchar)
{
    string res = string.Empty;

    MemoryStream ms = null;
    XmlTextWriter tw = null;

    try
    {
        XmlDocument doc = new XmlDocument();

        ms = new MemoryStream();
        tw = new XmlTextWriter(ms, Encoding.Unicode);

        doc.LoadXml(xml);

        tw.Formatting = Formatting.Indented;
        tw.Indentation = indentation;
        tw.IndentChar = indentchar;

        doc.WriteContentTo(tw);

        tw.Flush();
        ms.Flush();

        ms.Position = 0;

        StreamReader sr = new StreamReader(ms);

        res = sr.ReadToEnd();
    }
    catch (XmlException)
    {
    }
    finally
    {
        ms.Close();
        tw.Close();
    }

    return res;
}

[C#] String in Enum wandeln

public enum MyType
{
    Undef = 0,
    Type1 = 10,
    Type2 = 20,
    Type3 = 64
}

// Variante 1 mit Parse
string sType = &quot;Type1&quot;;
MyType t = (MyType)Enum.Parse(typeof(MyType), sType);

// Variante 2 mit TryParse
MyType a;
string sType = &quot;Type1&quot;;

// Inhalt von string &quot;sType&quot; bestimmen und in MyType wandeln
// Ergebnis in &quot;a&quot; ausgeben
if (Enum.TryParse<MyType->(sType, out a))
{
    ...
}

[Zedgraph] Grundgerüst für die Verwendung von Zedgraph

private void InitGraph()
{
    GraphPane myPane = zedGraph.GraphPane;
    zedGraph.IsShowPointValues = true;

    myPane.CurveList.Clear();
    myPane.GraphObjList.Clear();

    myPane.Legend.IsVisible = true;

    myPane.XAxis.Title.Text = "x";
    myPane.XAxis.MinorGrid.IsVisible = false;
    myPane.XAxis.MajorGrid.IsVisible = false;
    myPane.XAxis.Scale.MajorStep = 1.0;

    myPane.YAxis.Title.Text = "y'";
    myPane.YAxis.Title.FontSpec.FontColor = Color.Red;
    myPane.YAxis.MajorGrid.IsVisible = true;
    myPane.YAxis.MinorGrid.IsVisible = false;
    myPane.YAxis.MajorTic.IsOpposite = false;
    myPane.YAxis.MinorTic.IsOpposite = false;
    myPane.YAxis.Scale.Align = AlignP.Inside;
    myPane.YAxis.Scale.Min = 0.0;
    myPane.YAxis.Scale.MajorStep = 10.0;

    myPane.Title.Text = "x/y'";

    myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f);
    myPane.Fill = new Fill(Color.White, Color.AliceBlue, 45.0f);

    zedGraph.AxisChange();
}

private void ClearGraph()
{
    zedGraph.GraphPane.CurveList.Clear();
    zedGraph.AxisChange();
    zedGraph.Refresh();
}

private void FillGraph()
{
    this.ClearGraph();

    GraphPane myPane = zedGraph.GraphPane;

    ...
    
    zedGraph.AxisChange();
    zedGraph.Refresh();
}

[C#] Syntax Highlighting mit einer RichTextBox

// example from: http://www.codestructs.com/2011/11/syntax-highlighting-in-richtextbox_23.html
private void RichTextBox1_TextChanged(object sender, EventArgs e)
{
    int iSelStart = RichTextBox1.SelectionStart;
    int iSelLength = RichTextBox1.SelectionLength;

    string tokens = "(auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)";

    Regex rex = new Regex(tokens);

    MatchCollection mc = rex.Matches(RichTextBox1.Text);

    int iStart = RichTextBox1.SelectionStart;

    foreach (Match m in mc)
    {
        int iStartIndex = m.Index;
        int iStopIndex = m.Length;

        RichTextBox1.Select(iStartIndex, iStopIndex);
        RichTextBox1.SelectionColor = Color.Blue;
        RichTextBox1.SelectionStart = iStart;
        RichTextBox1.SelectionColor = Color.Black;
    }

    RichTextBox1.SelectionStart = iSelStart;
    RichTextBox1.SelectionLength = iSelLength;
}

Weiterführende Beispiele:

[C#] INI-Files lesen und schreiben

using System.Text;
using System.Runtime.InteropServices;

/// <summary>
/// freeware helper class for using INI-files
/// (W) 2012 by admin of codezentrale.de
///
/// usage:
///
/// IniFile _ini = new IniFile("c:\\testini.ini");
/// if (_ini != null)
/// {
///     string r = _ini.IniReadValue("section", "key", "default");
///     
///     if (_ini.IniWriteValue("section", "key", "value"))
///     {
///         ...
///     }
/// }
/// </summary>
public class IniFile
{
    private string _INIfile = string.Empty;

    [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileStringW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

    [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileStringW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);

    /// <summary>
    /// current INI-file
    /// </summary>
    public string IniFileName
    {
        get { return _INIfile; }
    }

    /// <summary>
    /// INIFile constructor
    /// </summary>
    /// <PARAM name="INIPath">INI file</PARAM>
    public IniFile(string INIfile)
    {
        _INIfile = INIfile;
    }
    /// <summary>
    /// write data to the INI-file
    /// </summary>
    /// <param name="section">Section name</PARAM>
    /// <param name="key">Key Name</PARAM>
    /// <param name="value">Value Name</PARAM>
    /// <returns>true if success</returns>
    public bool IniWriteValue(string section, string key, string val)
    {
        return WritePrivateProfileString(section, key, val, _INIfile);
    }

    /// <summary>
    /// read data value from the INI-file
    /// </summary>
    /// <param name="section"section name</PARAM>
    /// <param name="key">key name</PARAM>
    /// <param name="def">default value on error</param>
    /// <returns>Value or def on error</returns>
    public string IniReadValue(string section, string key, string def)
    {
        StringBuilder sb = new StringBuilder(255);

        int iCharsRead = GetPrivateProfileString(section, key, def, sb, (uint)sb.Capacity, _INIfile);
        
        return sb.ToString();
    }
}

[C#] Ausgewählte ListViewItems per Button-Klick verschieben

// funktioniert auch mit MultiSelect = true
// n items nach oben verschieben
private void btnUp_Click(object sender, EventArgs e)
{
    int ilevel = 0;

    ListView1.BeginUpdate();

    if (ListView1.SelectedItems.Count -> 0)
    {
        for (int i = 0; i < ListView1.Items.Count; i++)
        {
            if (ListView1.Items[i].Selected)
            {
                ilevel = i;
                if (ilevel - 1 ->= 0)
                {
                    ListViewItem lvitem = ListView1.Items[i];
                    ListView1.Items.Remove(lvitem);
                    ListView1.Items.Insert(ilevel - 1, lvitem);
                }
            }
        }
    }

    ListView1.EndUpdate();
}
// n items nach unten verschieben
private void btnDown_Click(object sender, EventArgs e)
{
    int iLevel = 0;

    ListView1.BeginUpdate();

    if (ListView1.SelectedItems.Count -> 0)
    {
        for (int i = ListView1.Items.Count - 1; i ->= 0; i--)
        {
            if (ListView1.Items[i].Selected)
            {
                iLevel = i;
                if (iLevel + 1 < ListView1.Items.Count)
                {
                    ListViewItem lvItem = ListView1.Items[i];
                    ListView1.Items.Remove(lvItem);
                    ListView1.Items.Insert(iLevel + 1, lvItem);
                }
            }
        }
    }

    ListView1.EndUpdate();
}

[C#] HTML-Seite mittels HttpWebRequest und HttpWebResponse laden

using System.IO;
using System.Net;

private string GetHtml(string url)
{
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    StreamReader sr = null;
    string html = string.Empty;

    try
    {
        request = (HttpWebRequest)HttpWebRequest.Create(url);
        response = (HttpWebResponse)request.GetResponse();

        sr = new StreamReader(response.GetResponseStream());

        html = sr.ReadToEnd();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
    finally
    {
        if (sr != null)
        {
            sr.Close();
            sr.Dispose();
            sr = null;
        }

        if (response != null)
        {
            response.Close();
            response = null;
        }

        if (request != null)
        {
            request = null;
        }
    }

    return html;
}