Monday, September 21, 2009

Writing to the text file in C# or VB.net

As a programmer we always need to deal with writing/reading to/from text files, it could be anything from error log, some debugging messages etc.
Below is the code in C# and VB.Net which accepts a message to write and a file name and appends it to given file if exists, else it will create a file and writes to it with current time stamp.
-------------------------------------------C# Code--------------------------------------
using System.IO;
class FileOperations
{
public static void WriteToTextFile(string strMessageToWrite, string strFilePath)
{
StreamWriter objStreamWriter;
try
{
if (File.Exists(strFilePath) == false)
{
objStreamWriter = File.CreateText(strFilePath);
}
else
{
objStreamWriter = File.AppendText(strFilePath);
}
objStreamWriter.WriteLine(DateTime.Now.ToString() + ": " + strMessageToWrite);
objStreamWriter.Close();
}
catch (IOException IOExp)
{
throw IOExp;
}
catch (Exception Ex)
{
throw Ex;
}
}
}
-------------------------------------------VB.Net Code-----------------------------------------------
Imports System.IO
Public Class FileOperations
Public Sub WriteToTextFile(ByVal strMessageToWrite As String, ByVal strFilePath As String)
Dim objStreamWriter As StreamWriter
Try
If File.Exists(strFilePath) = False Then
objStreamWriter = File.CreateText(strFilePath)
Else
objStreamWriter = File.AppendText(strFilePath)
End If
objStreamWriter.WriteLine(Date.Now & ": " & strMessageToWrite)
objStreamWriter.Close()
Catch IOExp As IOException
Throw IOExp
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
-----------------------------------------------------------------

Saturday, September 19, 2009

Basic Object Oriented Programming Concepts

In this post I will be discussing basics of Object Oriented programming(OOP) concepts using C# and/or VB.Net.
1) What is Object Oriented Programming?
Any software or application has some specific tasks to perform, and there are different ways to achieve it.
OOP is the way or technique which helps us building our application/software in terms of real world entities.
Main advantages of OOP approach
I)Flexibility for modifications,
II)Easy to maintain etc.

2) What are Objects, classes etc. and how they helpful/useful for our programming?
I will be adding stuffs soon.