Tuesday, November 25, 2008

Output Parameters in C# (.NET)


An output parameter is declared with the out modifier.

private static void ParamExample(double radius, out double Area, out double Perimeter)

{

const double pi = 22/7;

Area = pi * radius * radius;

Perimeter = 2 * pi * radius;

}

It is similar to a reference parameter except that the initial value of the caller-provided argument is unimportant.

double rad = 10.0;

double area;

double pm;

ParamExample(rad, out area, out pm);

Console.WriteLine("For a circle of radius {0} : Area is {1} and Perimeter is {2}", rad, area, pm);




output parameter in .NET


See also

How to get the return value from C# program (console application)

Command Line Arguments in C#

How to Return Multiple Values from a VBA Function


Readonly Fields in C# / Readonly Properties in C#

Read-only fields can be declared with a readonly modifier.

class Company

{

public static readonly string CompanyName = "VBADUD Inc";

}

Assignment to a readonly field can only occur as part of the field’s declaration or in a constructor in the same class.

class Company

{

// Assignment of Readonly value in Field declaration

public static readonly string CompanyName = "VBADUD Inc";

// Assignment of Readonly value in a static constructor

static Company()

{

CompanyName = "My Name";

}

}

Assigning the value to a readonly field outside the class will throw the following error:

Company.CompanyName = "My Company";

A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)


How to Get Remainder of a division using C# (.NET)

C# (.NET) Code to find odd / even numbers

In Visual Basic, Mod Function (x MOD Y) is used to get the remainder of a division. Similarly x % y is used to get the remainder in C#

public static void remainder()

{

short rem = 51 % 5;

Console.WriteLine(rem);

try

{

short input = System.Convert.ToInt16(Console.ReadLine());

if (input % 2 == 0)

{

Console.WriteLine("Even number");

}

else

{

Console.WriteLine("Odd Number");

}

}

catch (FormatException ex1)

{

Console.WriteLine("Please enter numerals only");

}

}


Insert Array to Excel Range using VSTO

Copy Array Values to Excel Range using VSTO

Many times we need to insert text to a contiguous Excel range using VSTO (like column headings). The following code does exactly that

private void InsertHeading()

{

string[] Header = { "Sno", "Product Code", "Product Name", "Quanity", "Price", "Total" };

Excel.Worksheet sht = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

Excel.Range myHeader = sht.get_Range("A1", "F1");

myHeader.Value2 = Header;

myHeader.Columns.AutoFit();

}


See Also

How to use .Net Array.Sort Function in VBA

Convert Dates to Arrays using Array Function

Object Arrays in C# using Indexers

Insert CSV File to Array using C#

Creating and Sorting Arrays in C#

Split Function in Visual Basic .Net

How to call a VSTO Addin Function from VBA

Call Method in Addin from Visual Basic Applications

VSTO Addins we write might contain good number of reusable components. The following article shows how to use them from external applications. This consists of the following steps:

1. Creating a VSTO Addin with a public method

2. Expose the VSTO Method for external use

3. Consume the VSTO Method from VBA

Creation of VSTO Excel Addin

Create a new project from Visual Studio - - > Office Projects - - > Excel 2007 Addin and call the project CallVSTOExample

This will automatically create necessary references and add required directives


VSTO Addin



using System;

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;

Create a new C# Class module and add the following code to it

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;

namespace CallVSTOExample

{

[ComVisible(true)]

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]

public interface IAddinVSTO

{

void SayHello();

}

[ComVisible(true)]

[ClassInterface(ClassInterfaceType.None)]

public class VSTOExample : IAddinVSTO

{

#region IAddinVSTO Members

public void SayHello()

{

Excel.Worksheet wks = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

Excel.Range myRange = wks.get_Range("A1", System.Type.Missing);

myRange.Value2 = "Hello";

}

#endregion

}

}

Here we have created one interface and have also created a class that implements the interface. The class has a simple method SayHello, which inserts “Hello” in cell A1 of active worksheet

The class must be public and should expose the IDispatch interface for it to be visible to COM

InterfaceIsIDispatch indicates an interface is exposed to COM as a dispinterface, which enables late binding only.

Exposing the method for external use

Add the following code to ThisAddin class

private VSTOExample utilities;

protected override object RequestComAddInAutomationService()

{

if (utilities == null)

utilities = new VSTOExample();

return utilities;

}

RequestComAddInAutomationService method returns an object in your add-in that can be used by other Microsoft Office solutions.

Override this method to expose an object in your add-in to other Microsoft Office solutions. This includes other add-ins and document-level customizations running in the same application process, VBA code, and external automation code.

The object that you return must be public, it must be visible to COM, and it must expose the IDispatch interface. If the object you return does not meet these requirements, the Visual Studio Tools for Office runtime will throw an InvalidCastException after it calls your implementation.

Compile the code and open the application (Excel) with the addin installed.

Excel VBA Code to call VSTO Method

The VSTOAddin that was created will be loaded as a COMAddin in Excel. The following code will retrieve the addin information

Sub Execute_VSTO_Addin_Macro()

Dim oAddin As COMAddIn

Dim oCOMFuncs As Object

Set oAddin = Application.COMAddIns("CallVSTOExample")

Set oCOMFuncs = oAddin.Object

oCOMFuncs.SayHello

End Sub

The Object property returns the object represented by the specified COMAddIn object. The VSTO function SayHello is called using the COMAddin’s object as shown above

See Also

How to use .Net Array.Sort Function in VBA

Property, indexer, or event 'Range' is not supported by the language; try directly calling accessor method 'Microsoft.Office.Interop.Excel._Worksheet.

A worksheet Range cannot be called directly as shown below

Excel.Worksheet wks = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

wks.Range("A1").value2 = "Hi";

Instead use the get_Range Method of Worksheet Class

Excel.Worksheet wks = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

0020Excel.Range myRange = wks.get_Range("A1", System.Type.Missing);

myRange.Value2 = "Hello";

See also :

Object Arrays in C# using Indexers

Properties in .NET / Get and Set Methods in .NET


The type or namespace name 'ComVisible' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'ComVisibleAttribute' could not be found (are you missing a using directive or an assembly reference?)

This error occurs when you are trying to use ComVisibleAttribute in a class without a reference to System.Runtime.InteropServices namespace

[ComVisible(true)]

public interface IAddinVSTO

{

void SayHello();

}

Should have a reference to System.Runtime.InteropServices namespace like shown below

using System.Runtime.InteropServices;

[ComVisible(true)]

public interface IAddinVSTO

{

void SayHello();

}




ComVisibleAttribute Error

What are assemblies in C#?

A C# assembly is the compiled output of the program. An assembly is the tangible output of a program, which might be an executable (.exe) or a library (.dll).

The output type of a C# program can be specified in Visual Studio or through command prompt

Saturday, November 15, 2008

How to Override methods in C#

Overriding functions in C#

Methods from base class can be overridden in the derived class and customized for necessity. This means the derived class can contain the member with the same name as that of the parent class

To override a method in the derived class :

  • The base class method must be defined virtual
  • Method in the derived class should be preceded by new or override keywords
  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
  • If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.
  • The base class method can be called from within the derived class using the base keyword.
  • The override, virtual, and new keywords can also be applied to properties, indexers, and events.

class BaseClass

{

virtual public string SayHi()

{

return( "Hi");

}

}

class DerivedClass : BaseClass

{

public override string SayHi()

{

return (base.SayHi() + " from derived");

}

}

If the base class is not declared as virtual, abstract or override, the compiler throws the following error:

'function1' : cannot override inherited member 'function2' because it is not marked "virtual", "abstract", or "override"

A method was overridden that was not explicitly marked as virtual, abstract, or override.

On the other hand, If the override or new keyword is missing the following error will occur

'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.

A variable was declared with the same name as a variable in a base class. However, the new keyword was not used. This warning informs you that you should use new; the variable is declared as if new had been used in the declaration.

How to access the method in a base class from the derived class

base keyword is used to access members of the base class from within a derived class

return (base.SayHi() + " from derived");

calls the SayHi method of the base class

,

How to override functions in .NET, .NET Function overriding, .NET how to access base class’s method in derived class, base keyword in .NET, virtual methods in .NET,

Type Inference in C# using var keyword

Implicitly Typed Local Variables in C#

Instead of explicitly declaring the variable of a particular type (int, short, string etc), one can define a variable of type ‘var’ and allowing the compiler to infer the type

For example,

var i = 10;

is equivalent to

int i = 10;

The inferred type may be a built-in type, an anonymous type, a user-defined type, a type defined in the .NET Framework class library, or any expression.

Implicit Typed Variables in .NET, .NET Variant, Var keyword in .NET,

Access Modifiers Comparison in Visual Basic .NET (VB.NET)

Keywords that specify access level are called as Access Modifers (e.g., Private, Public, Friend etc). Comparison of access levels of different keywords is given below:

Access modifier

Access level granted

Elements you can declare with this access level

Declaration context within which you can use this modifier

public

Unrestricted:

Any code that can see a public element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

protected

Derivational:

Code in the class that declares a protected element, or a class derived from it, can access the element

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

internal

Assembly:

Code in the assembly that declares an Internal element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

protectedinternal

Union of Protected and Internal:

Code in the same class or the same assembly as a protected Internal element, or within any class derived from the element's class, can access it

The protectedinternal accessibility means protected OR internal, not protected AND internal. In other words, a protectedinternal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

private

Declaration context:

Code in the type that declares a private element, including code within contained types, can access the element

Interfaces

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates


Access Modifiers Comparison in Visual Basic .NET (VB.NET)

Keywords that specify access level are called as Access Modifers (e.g., Private, Public, Friend etc). Comparison of access levels of different keywords is given below:

Access modifier

Access level granted

Elements you can declare with this access level

Declaration context within which you can use this modifier

Public

Unrestricted:

Any code that can see a public element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

Protected

Derivational:

Code in the class that declares a protected element, or a class derived from it, can access the element

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

Friend

Assembly:

Code in the assembly that declares a friend element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

ProtectedFriend

Union of Protected and Friend:

Code in the same class or the same assembly as a protected friend element, or within any class derived from the element's class, can access it

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

Private

Declaration context:

Code in the type that declares a private element, including code within contained types, can access the element

Interfaces

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates


Destructors in C# (.NET)

Unlike constructors, destructors are sparsely used in C# programs. This is because .NET Framework does an excellent job of memory management using garbage collection. However, it there are too many unmanaged resources in the application, they can be used as follows

class ClsTea : IRetail

{

//Variables

private string _locale;

private static string _brand;

// Class Destructor

~ ClsTea()

{

Console.WriteLine("Destructor Called");

// Code to release objects

}

// Class Default Constructor

public ClsTea()

{

Console.WriteLine("Constructor Called");

_brand = "N/A";

}

  • A class can only have one destructor.
  • Destructors cannot be inherited or overloaded.
  • Destructors cannot be called. They are invoked automatically.
  • A destructor does not take modifiers or have parameters.

Destructors in .NET, .NET Destructors, How to create a destructor in .NET, How to use destructors in .NET,

See also

How to create and use Static Constructors in C# (.NET)

How to create Default Constructors in C#

What is an Abstract Class / Abstract Classes in C#

What are the differences between Structs and Classes in C# (.NET)?

The struct type is suitable for representing lightweight. A struct would be less expensive. It is declared as

public struct Rect

{

public double height;

public double width;

public Rect(double d1, double d2)

{

height = d1;

width = d2;

}

public override string ToString()

{

return "(" + height +"," + width + ")";

}

}

It is used as

Rect r1 ;

r1.height = 10;

r1.width = 20;

Console.WriteLine(r1.ToString());

Rect r2 = new Rect(12, 23);

Console.WriteLine(r2.ToString());

  • Structs are value types and classes are reference types. That is when you pass the struct to a method you pass the value and not the reference.

Rect r2 = new Rect(12, 23);

Console.WriteLine("Rect Dimensions before passing:" + r2.ToString());

change_the_struct(r2);

Console.WriteLine("Rect Dimensions after passing:" + r2.ToString());

private static void change_the_struct(Rect Rectangle1)

{

Rectangle1.height = 100;

Rectangle1.width = 100;

Console.WriteLine("Rectangle Dimensions " + Rectangle1.ToString());

}

It will give the following output, which shows the struct is passed by value.

  • Unlike classes, structs can be instantiated without using a new operator. Static classes are an exception ()

Rect r1 ;

r1.height = 10;

r1.width = 20;

Console.WriteLine(r1.ToString());

  • Structs can declare constructors, but they must take parameters.

public struct Rect

{

public double height;

public double width;

public Rect(double d1, double d2)

{

height = d1;

width = d2;

}

}

  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  • Structs cannot have destructors, whereas classes can

.NET Structs, What are Structs, Example of Struct in .NET



See also :

How to Create Interfaces in .NET / Interfaces in .NET

How to Create Classes in C#

Properties in .NET / Get and Set Methods in .NET

Converting Date to British Date Format using C# (.NET)

Get Today’s date in British Format

Formatting dates are easy in C#. The following snippet gets the current date in British format.

private static string ConvertDate2British()

{

return String.Format("{0:dd-MM-yy}", DateTime.Now);

}

How to convert dates to British format using .NET, Date Conversion using .NET, .NET String.Format Method, Get Current Date using .NET, .NET Today Method

See also:

Formatting Date Input - DateFOrmat (SQL)

Get Size of a Particular Directory using C# (.NET)

Get Directory Size using C#

One way to find the size of entire directory (including all sub-directories) is to sum up the size of all files in those directories

The following code snippet adds the size of all the files to get the directory size

private static void GetDirSize(string rootdir)

{

try

{

long DirSize = 0;

DirectoryInfo[] DI = new DirectoryInfo(rootdir).GetDirectories("*.*", SearchOption.AllDirectories);

FileInfo[] FI = new DirectoryInfo(rootdir).GetFiles("*.*", SearchOption.AllDirectories);

foreach (FileInfo F1 in FI)

{

DirSize += F1.Length;

}

Console.WriteLine("Total Size of {0} is {1} bytes", rootdir, DirSize);

}

catch (DirectoryNotFoundException dEX)

{

Console.WriteLine("Directory Not Found " + dEX.Message);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

Get Directory Size using C#, Get SubDirectory Size using C#, SearchOption.AllDirectories in C#, How to Search All Directories using C#, FileSize using C#, How to get directory size using C#

Get Directory Size using .NET, Get SubDirectory Size using .NET, SearchOption.AllDirectories in .NET, How to Search All Directories using .NET, FileSize using .NET, How to get directory size using .NET



Directory Size using C#





Formatted Output using C# (Integer to Hexadecimal) / (Integer to Decimal) / (Integer to Exponential notations)

How to Display an Integer in Hexadecimal, Decimal and Scientific notations using C# (.NET)

Composite formatting can be used to format the output into various forms as shown below

private static void ListNumbersAsHexOctSciFormat()

{

try

{

Console.WriteLine("Decimal Hexadecimal Exponential (Scientific)");

for (int i = 1; i <>

{

Console.WriteLine("{0:D} \t{0:X} \t{0:E}",i );

}

}

catch (FormatException dEX)

{

Console.WriteLine("Formatting Exception" + dEX.Message);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

To convert a string use String.Format method

string S1 = String.Format("{0:X}", i);

Formatting Strings in C#, Formatted Output in C#, C# Convert Decimal to Hexadecimal, Decimal to Hexadecimal Conversion using C#, Integer to Scientific notation using C#, C# Scientific notations, C# Integer to Hexadecimal, C# Integer to Decimal, C# Integer to Exponential notations, .NET Integer to Decimal, .NET Integer to Exponential notations

Formatting Strings in .NET, Formatted Output in .NET, .NET Convert Decimal to Hexadecimal, Decimal to Hexadecimal Conversion using .NET, Integer to Scientific notation using .NET, .NET Scientific notations, .NET Integer to Hexadecimal

Get all Sub Directories under a folder using C# (.NET)

Get Sub Directories using C# (.NET)

Listing all subdirectories under a root directory using .NET (C#) is simple. You can use the DirectoryInfo..::.GetDirectories Method to list the directories

private static void ListDir(string rootdir)

{

try

{

DirectoryInfo[] DI = new DirectoryInfo(rootdir).GetDirectories("*.*", SearchOption.AllDirectories ) ;

foreach (DirectoryInfo D1 in DI)

{

Console.WriteLine(D1.FullName);

}

}

catch (DirectoryNotFoundException dEX)

{

Console.WriteLine("Directory Not Found " + dEX.Message);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

Here is the overload list of GetDirectories method

Name

Description

GetDirectories()()()

Returns the subdirectories of the current directory.

GetDirectories(String)

Returns an array of directories in the current DirectoryInfo matching the given search criteria.

GetDirectories(String, SearchOption)

Returns an array of directories in the current DirectoryInfo matching the given search criteria and using a value to determine whether to search subdirectories.

C# GetDirectories()()() Method, C# GetSubDirectories Method, Dir Function in VB.NET, Dir Function in C#, List All Directories using C#, List Sub Directories using C#, How to get all subdirectories using C#

.NET GetDirectories()()() Method, .NET GetSubDirectories Method, Dir Function in VB.NET, Dir Function in .NET, List All Directories using .NET, List Sub Directories using .NET, How to get all subdirectories using .NET

See also :

VBA Dir Function to Get Sub Directories

C# Get All Files from a Folder

OpenFileDialog in Visual Basic .Net

Directory Size using VB.Net

Get Size of a Particular Directory using C# (.NET)

Saturday, November 1, 2008

List all ReadOnly files in a directory using C# (.NET)

C# Get Read Only Files

The following code will retrieve the read-only files using LINQ and C#

private static void GetFilesFromDirectory(string DirPath)

{

try

{

DirectoryInfo Dir = new DirectoryInfo(DirPath);

FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly );

var query = from FI in FileList

where FI.IsReadOnly == true

select FI.FullName + " " + FI.LastWriteTime;

foreach (string s1 in query )

{

Console.WriteLine(s1);

}

}

catch (Exception ex)

{

Console.WriteLine(ex.Message );

}

}

The above can (and mostly is) done by the following way

FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly );

foreach (FileInfo F1 in FileList)

{

if (F1.IsReadOnly == true)

{

Console.WriteLine(F1.FullName );

}

}

List ReadOnly files using C#, Retrieve Read-Only files using C#, Get Read Only Files using C#, List ReadOnly files using .NET, Retrieve Read-Only files using .NET, Get Read Only Files using .NET

How to Filter files that are modified in a specific day using C#

C# GetFiles with Date Filter

Here is a snippet using C# and LINQ, which will retrieve the files from a directory for a specific date

private static void GetFilesFromDirectory(string DirPath)

{

try

{

DirectoryInfo Dir = new DirectoryInfo(DirPath);

FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly );

var query = from FI in FileList

where FI.LastWriteTime.Date == DateTime.Now.Date

select FI.FullName + " " + FI.LastWriteTime;

foreach (string s1 in query )

{

Console.WriteLine(s1);

}

}

catch (Exception ex)

{

Console.WriteLine(ex.Message );

}

}

Filter files by Date using C# GetFiles, DirectoryInfo.GetFiles method in C#, Filter files by date using DirectoryInfo, C# Get Files modified within a week, Filter files by Date using .NET GetFiles, DirectoryInfo.GetFiles method in .NET, Filter files by date using DirectoryInfo, .NET Get Files modified within a week

C# Get Files Greater than Specific Size using Linq

List files based on FileSize using C#

C# and LINQ can be combined to do wonders; here is a sample of that. The following snippet extracts the files that are more thsn 345 KB

private static void GetFilesFromDirectory(string DirPath)

{

try

{

DirectoryInfo Dir = new DirectoryInfo(DirPath);

FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly );

var query = from FI in FileList

where FI.Length > 340000

select FI.FullName + " " + FI.Length.ToString() ;

foreach (string s1 in query )

{

Console.WriteLine(s1);

}

}

catch (Exception ex)

{

Console.WriteLine(ex.Message );

}

}

Extract files based on Size in C#, Extract files greater than 1GB using C#, C# List files based on Size, Filter by FileSize using C#, Extract files based on Size in .NET, Extract files greater than 1GB using .NET, .NET List files based on Size, Filter by FileSize using .NET, Extract files based on Size in LINQ , Extract files greater than 1GB using LINQ , LINQ List files based on Size, Filter by FileSize using LINQ

C# Get All Files from a Folder

List all files from a folder using C# / List all files from folder and its subdirectories using C#

The following code lists all the files from the specifed folder and its sub folders

To list all Excel files using C#, modify the first argument to “*.xls”

private static void GetFilesFromDirectory(string DirPath)

{

try

{

DirectoryInfo Dir = new DirectoryInfo(DirPath);

FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories );

foreach (FileInfo FI in FileList )

{

Console.WriteLine(FI.FullName);

}

}

catch (Exception ex)

{

Console.WriteLine(ex.Message );

}

}

The following wildcard specifiers are permitted in searchPattern.

Wildcard character

Description

*

Zero or more characters.

?

Exactly one character.

Search for Word files starting with “Proposal” using C# in Current Directory

FileInfo[] FileList = Dir.GetFiles("Proposal*.doc", SearchOption.TopDirectoryOnly );

SearchPattern for files in C#, C# Dir Function SearchPatterns, List All files using C#, C# Dir Function, C# List of Files, How to get the list of files using C#,

Move and Overwrite Files in C# (.NET)

Moving Files in C# (.NET)

File.Move method can be used to move the file from one path to another. This method works across disk volumes, and it does not throw an exception if the source and destination are the same.

private static bool MoveFile(string sSource, string sDestn)

{

try

{

if (File.Exists(sSource) == true)

{

File.Move(sSource, sDestn, true);

return true;

}

else

{

Console.WriteLine("Specifed file does not exist");

return false;

}

}

catch (FileNotFoundException exFile)

{

Console.WriteLine("File Not Found " + exFile.Message);

return false;

}

catch (DirectoryNotFoundException exDir)

{

Console.WriteLine("Directory Not Found " + exDir.Message);

return false;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return false;

}

}

You cannot use the Move method to overwrite an existing file. If you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. To overcome this you can use the combination of Copy and Delete methods

private static bool MoveAndOverWrite(string sSource, string sDestn)

{

try

{

if (File.Exists(sSource) == true)

{

if (File.Exists(sDestn) == true)

{

File.Copy(sSource, sDestn, true);

File.Delete(sSource);

return true;

}

else

{

File.Move(sSource, sDestn);

return true;

}

}

else

{

Console.WriteLine("Specifed file does not exist");

return false;

}

}

catch (FileNotFoundException exFile)

{

Console.WriteLine("File Not Found " + exFile.Message);

return false;

}

catch (DirectoryNotFoundException exDir)

{

Console.WriteLine("Directory Not Found " + exDir.Message);

return false;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return false;

}

}



Moving and Overwriting files using C#
Move Files using .NET, Move and Overwrite files using .NET, Cannot create a file exception in .NET, .NET File.Move method, .NET FileMove, .NET File Copy

Delete Files using C# / Delete Files using .NET

The following snippet shows a simple way to delete specified file

private static bool DeleteFile(string sFileName)

{

try

{

if (File.Exists(sFileName) == true)

{

File.Delete(sFileName);

return true;

}

else

{

Console.WriteLine("File doesnot exist");

return false; }

}

catch (UnauthorizedAccessException ex)

{

// File in Use

Console.WriteLine("You do not have required permission for this operation " + ex.Message);

return false;

}

catch (IOException exIO)

{

// File in Use

Console.WriteLine("File in use " + exIO.Message);

return false;

}

catch (Exception ex)

{//Common Exception

Console.WriteLine(ex.Message);

return false;

}

}



Exception in File Delete (C#)


.NET Kill Method, C# File Class, C# Delete Method

See Also:

Move and Overwrite Files in C# (.NET)

VBA Send File to Recycle Bin

Clean Temp (.tmp) and Word Backup files (.wbk) using Word VBA

Copying Files using .Net Functions

Delete Temporary Files

Copy Files using C# / Copy files using .NET

File.Copy method can be used for copying the files. The function with two arguments copies an existing file to a new file; overwriting a file of the same name is not allowed. However, overwriting can be done by setting a flag in the third parameter of the overloaded function.

private static bool CopyFiles(string sSource, string sDestn)

{

try

{

if (File.Exists(sSource) == true)

{

File.Copy(sSource, sDestn);

return true;

}

else

{

Console.WriteLine("Specifed file does not exist");

return false;

}

}

catch (FileNotFoundException exFile)

{

Console.WriteLine("File Not Found " + exFile.Message);

return false;

}

catch (DirectoryNotFoundException exDir)

{

Console.WriteLine("Directory Not Found " + exDir.Message);

return false;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return false;

}

}

The function can be invoked by

CopyFiles (@"C:\Temp\DotNetDud\Sample.txt", @"C:\Temp\DotNetDud\CSharpSample\Sample_Bkup.txt");

Overwriting files in C#

The above function will throw IOException if the destination file exists. To overcome this you can use the following

File.Copy(sSource, sDestn, true );




FileCopy IOException

Check if file exists using C# (.NET)

Check Existence of File using C# (.NET)

Exists method of the System.IO.File class can be used to check if a file exists in a given location.

private static bool Check_file_Existence(string sFileName)

{

try

{

if (File.Exists(sFileName) == true)

{return true;

}

else

{ return false; }

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return false;

}

}

, IsExist Method in .NET, .NET File Class, .NET Exists Method

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005