Thursday, August 27, 2009

Working With File System


System.IO provides all the required classes, methods and properties for manipulating with Files and Directories. C#.net provides synchronous and a synchronous read/write operation using the following namespaces.
System.IO.FileSystemInfo is the Base class for File System operations. FileSystemInfo includes members like Delete (Delete File or Directory), GetHashCode, GetLifeTimeService, GetType ,Refresh, ToString, FullPath and OriginalPath.
Sysntem.IO.DirectoryInfo provides methods for creating, moving and deleting directories. DirectoryInfo includes members like Create, CreateSubDirecory, Delete, GetAccessControl,GetDirectories, GetFiles, GetFileSystemInfos, MoveTo,Refresh, SetAccessControl,Atributes, Exists, FullName, LastAccess Details, Parent and Name
System.IO.FileInfo provides methods for creating, appending, opening, moving and deleting files. FileInfo includes members like AppendText, CopyTo, Create,Decrypt , Delete, Encrypt, Finalize, GetAccessControl, MoveTo, Open, OpenRead, OpenText, OpenWrite, Refresh, SetAccessControl, Atributes, Exists, FullName, LastAccess Details and IsReadOnly.
System.IO.Stream Provides generic view of the Sequence of byte. Mainly used with File manipulation operations.

How to Read Text from File:
Following is the code sample to read the text from file using the ReadAllLines or ReadAllText

using System;
using System.IO;
namespace NinadBlog.Examples
{
class FileRead
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
using (StreamReader srReadFile = new StreamReader("NinadBlogFileTest.txt"))
{
String strLine;
// Read and display lines from the file until the end of
while ((strLine = srReadFile.ReadLine()) != null)
{
Console.WriteLine(strLine);
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file could not be read: " & ex.Message);
}
}
}
}

How to write Text File:
Following is the code sample to write text in the file using the WriteAll.

using System;
using System.IO;
namespace NinadBlog.Examples
{
class FileWrite
{
public static void Main()
{
try
{
// Create an instance of StreamWriter to write in a file.
using (StreamWriter swWriter = new StreamWriter("NinadBlogFileTest.txt"))
{
// Add some text to the file.
sw.Write("This is the WriteStream Example on Ninad CS blog.");
sw.WriteLine("-------------------");
sw.WriteLine("By Ninad Pradeep Pandit");
sw.close();
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file write Exception: " & ex.Message);
}
}
}
}

Best Practices
1. If you are going to reuse an object several times, consider using the instance method of DirectoryInfo/FileInfo or Syste instead of the corresponding static methods of the System.IO.Directory/File, to avoid un-necessary security check every time.
2. Make sure we give correct access to file after creation, By default, full read/write access is granted to all users.
3. Do not override the Close method for Stream. Close method, instead, put all of the Stream cleanup logic in the Dispose method. For more information

Friday, August 21, 2009

Exception Handling


try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
Exception handling is a mechanisum to identify and deal with the exceptional flows in your code durring the run time. Exception handling in C# uses try, catch, and finally key words.
tryis the block to identify the exceptions.
catchis the block, who is called automatically if any exception occured in the try block.
finally is the block, who is resposible for the the clean-up activities.
throw is the keyword to generate or redirect the exception.
Exceptions are of two types, like exceptions generated by an executing program (Application Exception) or common language runtime (System Exception). System. Exception is the base class for all exceptions.

Exception Class Properties
Exception class properties help to identify the code location, type, exception reason, StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.
InnerException property maintains the relationship within the two or more exceptions. The OuterException has thrown in response to Inner Exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately.
Supplementary information or description about the current exception has been stored in the Data property.
HelpLink is generally used to provide additional information about the exception. This property can hold URL.
Source maintains the details about the application or object that causes an error or exception.

Best Practices
1. Use throw instead of throw Ex. This will help you to trace the exception to right place.
2. Try to catch as many as Application Exception(s) you can. Never keep your try block unattended.
3. Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected.
4. Try to use custom Exception only if System. Exception is not enough to support your need.
5. Do not throw an exception as a return code. Throwing an Exception is much more costlier than returing code.

Summary
1. Exceptions are types that all ultimately derive from System.Exception.
2. Use a try block around the statements that might throw exceptions.
3. Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.
4. If no exception handler for a given exception is present, the program stops executing with an error message.
5. Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.
6. If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.
7. Exceptions can be explicitly generated by a program by using the throw keyword.
8. Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.
9. Code in a finally block is executed even if an exception is thrown. Use a finally block to release resources, for example to close any streams or files that were opened in the try block.