Tuesday, January 26, 2010

Writing a text file in C#

Here is a simple C# segment of code that writes values to a text/ini file. It's from my NetPinger Application. It uses StreamWriter and the system.IO libraries of .NET.

using System.IO;

try

{

FileStream file = new FileStream

("config.ini",

FileMode.OpenOrCreate);

StreamWriter sr = new StreamWriter(file);

sr.WriteLine("[NetPinger Configuration]");

sr.WriteLine(AppTitle);

sr.WriteLine();

sr.WriteLine("[LDAP String]");

sr.WriteLine(LDAP);

sr.WriteLine();

sr.WriteLine("[Site Location]");

sr.WriteLine(Site);

sr.WriteLine();

sr.WriteLine("[SMTP Server]");

sr.WriteLine(SMTP);

sr.WriteLine();

sr.WriteLine("[Query Intervals]");

try

{

sr.WriteLine(txtQuery.Value.ToString());

}

catch (Exception ex)

{

mnuNotify.ShowBalloonTip

(5000,

"NetPinger 2010",

ex.Message,

ToolTipIcon.Warning);

toolStripStatusLabel1.Text =

ex.Message;

}

sr.Close();

file.Close();

mnuNotify.ShowBalloonTip

(5000,

"NetPinger 2010",

"Configuration Saved!",

ToolTipIcon.Info);

toolStripStatusLabel1.Text =

"Configuration Saved!";

lblSite.Text = Site;

lblSite.Left = Width - (lblSite.Width + 20);

}

catch (Exception ex)

{

mnuNotify.ShowBalloonTip

(5000,

"NetPinger 2010",

ex.Message,

ToolTipIcon.Warning);

toolStripStatusLabel1.Text =

ex.Message;

}

No comments:

Post a Comment