(http://|ftp://)([\w-\.)(\.)([a-zA-Z]+)
C# Tutorial (Chapter - 1) Introduction about C# and .Net framework(1 :- .Net Plateform)
I :-.Net Plateform :-
The Microsoft® .NET platform provides all of the tools and technologies that
you need to build distributed Web applications. It exposes a languageindependent,
consistent programming model across all tiers of an application
while providing seamless interoperability with, and easy migration from,
existing technologies. The .NET platform fully supports the Internet’s platformneutral, standards-based technologies, including HTTP, Extensible Markup
Language (XML), and Simple Object Access Protocol (SOAP).
II :-The .NET Building Block Services :-
The .Net building block services are distributed programmable services that are availaible in both offline and online.A service can be invoked on stand alone computer not connected to the internet,provided by the server which is running inside from the company oer accessed by internet, This service can be used from the plateform which supports SOAP.Services include identity, notification and messaging,
personalization, schematized storage, calendar, directory, search, and software
delivery.
III :-The .NET Enterprise Servers :-
1: Microft Sql server - 2000
2: Microsoft Biztalk sever - 2000
3: Microsoft Host integration server - 2000
4: Microsoft Exchange 2000 Enterprise server
5: Microst Application center - 2000
6: Microsoft Internet security server - 2000
Microsoft Sql server - 2000 :- Supports XML functionality, support for Worldwide Web Consortium (W3C) standards, manipulate XML data by using Transact SQL (T-SQL), flexible Web-based analysis, and secure access to your data over the Web by using HTTP.
Microsoft Internet security server - 2000 :- Provides secure, fast, and manageable Internet connectivity. Internet Security and multilayer enterprise firewall and a scalable high-performance Web cache. It builds on Windows 2000 security.
Microst Application center - 2000 :- Provides a deployment and management tool for high-availability Web applications.
Microsoft Exchange 2000 Enterprise server :- Builds on the powerful Exchange messaging and collaboration technology by ntroducing new features, and further increasing the reliability,scalability, and performance of its core architecture.
Microsoft Biztalk sever - 2000 :- Provides enterprise application integration (EAI), business-to-business integration and to build dynamic business processes,the span applications and plate forms.
Microsoft Host integration server - 2000 Provides the best way to embrace Internet, intranet, and client/server technologies.
IV :-The .NET Framework Components :-
1:-Common Language Runtime
2:- Base Class Library
3:- ADO.NET: Data and XML
4:- Web Forms and Services
5:- User Interface
CLR(Comman Language Runtime) :- Central to the .NET framework is its run-time execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed
managed code.However, before it can be executed by the CLR, any sourcecode that we develop (in C# or some other language) needs to be compiled. Compilation occurs in two steps in .NET:
1. Compilation of source code to Microsoft Intermediate Language (MS-IL)
2. Compilation of IL to platform-specific code by the CLR
Components of CLR :-
1 :-Class loader : Manages metadata, as well as the loading and layout of classes.
ClassLoader classLoader = TestClass.getClassLoader();
URL url = cl.getResource("someFileName");
2 :-Garbage collector (GC) :-The garbage collector is .NET's answer to memory management,Having the application code responsible for de-allocating memory is the technique used by lower-level,high-performance languages such as C++. It is efficient, and it has the advantage that (in general)resources are never occupied for longer than unnecessary. The big disadvantage, however, is the frequency of bugs. Code that requests memory also should explicitly inform the system when it no longer requires that memory. However, it is easy to overlook this, resulting in memory leaks.Provides automatic lifetime management of all of your objects. This is a multiprocessor, scalable garbage collector.
3 :-Security engine :-It based on the origin of the code.
4 :-Debug engine :- Debug your program and trace the execution of code.
5:-Code manager :-Manages the code execution.
6 :-Exception manager :- It provides structured exception management,which is integrated with Windows Structured Exception Handling (SEH),provides all the system exception classes.
7 :-Thread support :-Supports multi threaded programming.
8 :-COM :-Provides Interoperability class and marshalling to and from COM.
9 :-Type checker :-This will not allow unsafe typecasting and uninitialized variables Il verifies guaranteed type safety.
10 :-Microsoft intermediate language :-Converts MSIL to native code.
11 :- Base Class Library :- Executes run time.
2:-Base Class library :- This library contains namespaces like header files in C,C++,It expose features at run time and provide some high services.
I am mentioning namespace and about their services :-
System.Collections :- You can see all the interfaces and classes included in this namespace from below link :-
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
The Microsoft® .NET platform provides all of the tools and technologies that
you need to build distributed Web applications. It exposes a languageindependent,
consistent programming model across all tiers of an application
while providing seamless interoperability with, and easy migration from,
existing technologies. The .NET platform fully supports the Internet’s platformneutral, standards-based technologies, including HTTP, Extensible Markup
Language (XML), and Simple Object Access Protocol (SOAP).
II :-The .NET Building Block Services :-
The .Net building block services are distributed programmable services that are availaible in both offline and online.A service can be invoked on stand alone computer not connected to the internet,provided by the server which is running inside from the company oer accessed by internet, This service can be used from the plateform which supports SOAP.Services include identity, notification and messaging,
personalization, schematized storage, calendar, directory, search, and software
delivery.
III :-The .NET Enterprise Servers :-
1: Microft Sql server - 2000
2: Microsoft Biztalk sever - 2000
3: Microsoft Host integration server - 2000
4: Microsoft Exchange 2000 Enterprise server
5: Microst Application center - 2000
6: Microsoft Internet security server - 2000
Microsoft Sql server - 2000 :- Supports XML functionality, support for Worldwide Web Consortium (W3C) standards, manipulate XML data by using Transact SQL (T-SQL), flexible Web-based analysis, and secure access to your data over the Web by using HTTP.
Microsoft Internet security server - 2000 :- Provides secure, fast, and manageable Internet connectivity. Internet Security and multilayer enterprise firewall and a scalable high-performance Web cache. It builds on Windows 2000 security.
Microst Application center - 2000 :- Provides a deployment and management tool for high-availability Web applications.
Microsoft Exchange 2000 Enterprise server :- Builds on the powerful Exchange messaging and collaboration technology by ntroducing new features, and further increasing the reliability,scalability, and performance of its core architecture.
Microsoft Biztalk sever - 2000 :- Provides enterprise application integration (EAI), business-to-business integration and to build dynamic business processes,the span applications and plate forms.
Microsoft Host integration server - 2000 Provides the best way to embrace Internet, intranet, and client/server technologies.
IV :-The .NET Framework Components :-
1:-Common Language Runtime
2:- Base Class Library
3:- ADO.NET: Data and XML
4:- Web Forms and Services
5:- User Interface
CLR(Comman Language Runtime) :- Central to the .NET framework is its run-time execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed
managed code.However, before it can be executed by the CLR, any sourcecode that we develop (in C# or some other language) needs to be compiled. Compilation occurs in two steps in .NET:
1. Compilation of source code to Microsoft Intermediate Language (MS-IL)
2. Compilation of IL to platform-specific code by the CLR
Components of CLR :-
1 :-Class loader : Manages metadata, as well as the loading and layout of classes.
ClassLoader classLoader = TestClass.getClassLoader();
URL url = cl.getResource("someFileName");
2 :-Garbage collector (GC) :-The garbage collector is .NET's answer to memory management,Having the application code responsible for de-allocating memory is the technique used by lower-level,high-performance languages such as C++. It is efficient, and it has the advantage that (in general)resources are never occupied for longer than unnecessary. The big disadvantage, however, is the frequency of bugs. Code that requests memory also should explicitly inform the system when it no longer requires that memory. However, it is easy to overlook this, resulting in memory leaks.Provides automatic lifetime management of all of your objects. This is a multiprocessor, scalable garbage collector.
3 :-Security engine :-It based on the origin of the code.
4 :-Debug engine :- Debug your program and trace the execution of code.
5:-Code manager :-Manages the code execution.
6 :-Exception manager :- It provides structured exception management,which is integrated with Windows Structured Exception Handling (SEH),provides all the system exception classes.
7 :-Thread support :-Supports multi threaded programming.
8 :-COM :-Provides Interoperability class and marshalling to and from COM.
9 :-Type checker :-This will not allow unsafe typecasting and uninitialized variables Il verifies guaranteed type safety.
10 :-Microsoft intermediate language :-Converts MSIL to native code.
11 :- Base Class Library :- Executes run time.
2:-Base Class library :- This library contains namespaces like header files in C,C++,It expose features at run time and provide some high services.
I am mentioning namespace and about their services :-
System.Collections :- You can see all the interfaces and classes included in this namespace from below link :-
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
C# Tutorials
Hello to all, My next thread is about C#,In my next thread i will divide the C# thread into chapters each chapter will contain all the details about C# and .Net framework its a step by step process so go through to all the thread and please post a comment or email me at saurabhjnumca@gmail.com about this thread please give critics about this thread.If you will study the coming thread then you will able to explain about .net and you can easily code in C# .
Regards,
Saurabh Singh
Regards,
Saurabh Singh
How to create a session manager in .Net ?
To create a SessionManager to save User objects in memory. It would be HashMap of HaspMaps.
It can be used as:
SessionManager MySessionManager= New SessionManager()
Student S1 = New Student ("Saurabh");
Student S2 = New Student ("Sandeep");
Student S3 = New Student ("Deepak");
//To create session
MySessionManager.createSession(S1);
MySessionManager.createSession(S2);
//SAVING S1 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S1, "Physics", phyisicsMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S1, "Chemistry",chemistryMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S1, "Mathematics" ,mathsMarks);
//SAVING S2 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S2, "Physics", phyMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85)
MySessionManager.Save(S2, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S2, "Mathematics" ,mathsMarks);
//SAVING S3 MARKS. NOTE: SESSION OF S3 IS NOT AVAILABLE. SO FIRST SESSION OF
S3 SHOULD BE CREATED AND THEN DATA SHOULD BE SAVED
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S3, "Physics", phyMarks); //”Physics” is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S3, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S3, "Mathematics" ,mathsMarks);
///How to retrieve data
Out.Print ("Phyiscis Marks of S1," & MySessionManager.get(S1, "Physics").marks);
Out.Print ("Phyiscis Marks of S3," & MySessionManager.get(S1, "chemistry").marks);
IN REAL WORLD SCENARIO, S1, S2, S3 SHOULD NOT BE PASSED TO
MYSESSIONMANAGER. THEY WOULD BE OBTAINED FROM CONTEXT.
It can be used as:
SessionManager MySessionManager= New SessionManager()
Student S1 = New Student ("Saurabh");
Student S2 = New Student ("Sandeep");
Student S3 = New Student ("Deepak");
//To create session
MySessionManager.createSession(S1);
MySessionManager.createSession(S2);
//SAVING S1 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S1, "Physics", phyisicsMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S1, "Chemistry",chemistryMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S1, "Mathematics" ,mathsMarks);
//SAVING S2 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S2, "Physics", phyMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85)
MySessionManager.Save(S2, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S2, "Mathematics" ,mathsMarks);
//SAVING S3 MARKS. NOTE: SESSION OF S3 IS NOT AVAILABLE. SO FIRST SESSION OF
S3 SHOULD BE CREATED AND THEN DATA SHOULD BE SAVED
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S3, "Physics", phyMarks); //”Physics” is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S3, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S3, "Mathematics" ,mathsMarks);
///How to retrieve data
Out.Print ("Phyiscis Marks of S1," & MySessionManager.get(S1, "Physics").marks);
Out.Print ("Phyiscis Marks of S3," & MySessionManager.get(S1, "chemistry").marks);
IN REAL WORLD SCENARIO, S1, S2, S3 SHOULD NOT BE PASSED TO
MYSESSIONMANAGER. THEY WOULD BE OBTAINED FROM CONTEXT.
Tech-Giant(Jargons.. for Professionals): How to take Screenshot of panel,control and save it in a JPG format ?
How to take Screenshot of panel,control and save it in a JPG format ?
You can create a bitmap of screen and then save it give the stream or fileName and then dispose the object of screenshot.
Bitmap theScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
theScreenShot.Save(stream_or_filename, ImageFormat.Jpeg);
theScreenShot.Dispose();
Another way to save the panel as a jpg format and you can take a print of your control using below method.
Use this event on your form :-
_document.PrintPage += new PrintPageEventHandler(document_PrintPage);
/// Prepare the page to be print for the area of the control to be printed.
private void document_PrintPage(object sender, PrintPageEventArgs e)
{
this.Dock = System.Windows.Forms.DockStyle.None;
this.Size = Temp_Image.Size;
//Takes away focus from any printed controls to make sure output is what we want.
this.Focus();
this.Refresh();
this.DrawToBitmap(Temp_Image, New System.Drawing.Rectangle(0, 0, Temp_Image.Width, Temp_Image.Height));
this.Dock = System.Windows.Forms.DockStyle.Fill;
e.Graphics.DrawImage(Temp_Image, e.MarginBounds);
e.Graphics.Clip = new Region(e.MarginBounds);
}
By this method you can print your control you just pass the object of your control (control will be panel,treeView,listView)and this will calculate the height ,width and then call the print method ,print preview or save as jpg file.
Bitmap theScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
theScreenShot.Save(stream_or_filename, ImageFormat.Jpeg);
theScreenShot.Dispose();
Another way to save the panel as a jpg format and you can take a print of your control using below method.
Use this event on your form :-
_document.PrintPage += new PrintPageEventHandler(document_PrintPage);
/// Prepare the page to be print for the area of the control to be printed.
private void document_PrintPage(object sender, PrintPageEventArgs e)
{
this.Dock = System.Windows.Forms.DockStyle.None;
this.Size = Temp_Image.Size;
//Takes away focus from any printed controls to make sure output is what we want.
this.Focus();
this.Refresh();
this.DrawToBitmap(Temp_Image, New System.Drawing.Rectangle(0, 0, Temp_Image.Width, Temp_Image.Height));
this.Dock = System.Windows.Forms.DockStyle.Fill;
e.Graphics.DrawImage(Temp_Image, e.MarginBounds);
e.Graphics.Clip = new Region(e.MarginBounds);
}
By this method you can print your control you just pass the object of your control (control will be panel,treeView,listView)and this will calculate the height ,width and then call the print method ,print preview or save as jpg file.
Order of Event firing in ASP.Net
Event firing order becomes critically important when you add event handling code to master pages and the content forms based on them. The following events occur when ASP.NET renders a page. I’ve listed these events in the order in which they occur.
1 :-Content Page Pre Initializes
2 :-Master Page Child Controls Initialize
3 :-Content Page Child Controls Initialize
4 :-Master Page Initializes
5 :-Content Page Initializes
6 :-Content Page Initialize Complete
7 :-Content Page Pre Loads
8 :-Content Page Loads
9 :-Master Page Loads
10 :-Master Page Child Controls Load
11 :-Content Page Child Controls Load
12 :-Content Page Load Complete
1 :-Content Page Pre Initializes
2 :-Master Page Child Controls Initialize
3 :-Content Page Child Controls Initialize
4 :-Master Page Initializes
5 :-Content Page Initializes
6 :-Content Page Initialize Complete
7 :-Content Page Pre Loads
8 :-Content Page Loads
9 :-Master Page Loads
10 :-Master Page Child Controls Load
11 :-Content Page Child Controls Load
12 :-Content Page Load Complete
Lambda Expressions in C#
Lambda expressions makes the searching life much easier.Have a look on this example :-
public class TestLambdaProgram
{
public static void Main( string[] args )
{
List names = new List();
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
You can print the whole list using this method :-
new List(names ).foreach(name => Console.WriteLine(name));
public class TestLambdaProgram
{
public static void Main( string[] args )
{
List
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
You can print the whole list using this method :-
new List
Basics of .Net (What is IL,CLR,CTS,CLS ?)
1: IL(Intermediate Language) :-(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. This IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler. Microsoft Intermediate Language (MSIL) is a language used as the output of a number of compilers (C#, VB, .NET, and so forth). The ILDasm (Intermediate Language Disassembler) program that ships with the .NET Framework SDK (FrameworkSDK\Bin\ildasm.exe) allows the user to see MSIL code in human-readable format. By using this utility, we can open any .NET executable file (EXE or DLL) and see MSIL code.
MSIL commands are as follows:
ldstr string :—loads the string constant onto the stack.
call function(parameters) :—calls the static function. Parameters for the function should be loaded onto the stack before this call.
pop :—pops a value from the stack. Used when we don't need to store a value in the variable.
ret :—returns from a function.
I will discuss about MSIL in my next article.
2 :- CLR(Comman Language Runtime) Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.It is the implementation of CLI .The core runtime engine in the microsoft .net framework for executing assemblies. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Internet Exlorer is the example of hosting CLR. CLR have following qualities :-
Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.
Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.
Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL
code.
3 :- CTS(Comman Type System) :- In order that two language communicate smoothly CLR has CTS (Common Type System).Example
in VB you have “Integer” and in C++ you have “long” in c u have "int" these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can 1. Basic .NET Framework communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and
“int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.
4 :-CLS(Common Language Specification) :- This is a subset of the CTS which all .NET languages are expected to support. It was always a
dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
MSIL commands are as follows:
ldstr string :—loads the string constant onto the stack.
call function(parameters) :—calls the static function. Parameters for the function should be loaded onto the stack before this call.
pop :—pops a value from the stack. Used when we don't need to store a value in the variable.
ret :—returns from a function.
I will discuss about MSIL in my next article.
2 :- CLR(Comman Language Runtime) Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.It is the implementation of CLI .The core runtime engine in the microsoft .net framework for executing assemblies. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Internet Exlorer is the example of hosting CLR. CLR have following qualities :-
Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.
Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.
Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL
code.
3 :- CTS(Comman Type System) :- In order that two language communicate smoothly CLR has CTS (Common Type System).Example
in VB you have “Integer” and in C++ you have “long” in c u have "int" these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can 1. Basic .NET Framework communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and
“int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.
4 :-CLS(Common Language Specification) :- This is a subset of the CTS which all .NET languages are expected to support. It was always a
dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
What are different types of JIT ?
In .net there are three type of JIT.JIT compiler is a part of the runtime execution environment.
Three JIT are following :-
Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.
Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is
used for execution.
Three JIT are following :-
Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.
Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is
used for execution.
What is Manifest in .net ?
An assembly manifest contains all the metadata.It means Assembly metadata is stored in Manifest and it needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes.Some points are given please go through it :-
1:- The assembly manifest can be stored in either a Portable Executable file an .exe or dll file with Microsoft intermediate language (MSIL) code or in a standalone Portable Executable file that contains only assembly manifest information.
These four items
1 :- assembly name
2 :- version number
3 :- culture
4 :- strong name information
These four make up the assembly's identity.
Assembly name: A string which specifying the assembly's name.
Version number: A major and minor version number, and a revision and build number. The clr uses these numbers to enforce version policy. Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
their individual folders.
Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information.
Satellite Assembly :- An assembly with culture information is automatically assumed to be a satellite assembly.
Strong name information: The public key from the publisher if the assembly has been given a strong name.
List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.
Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.
Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
1:- The assembly manifest can be stored in either a Portable Executable file an .exe or dll file with Microsoft intermediate language (MSIL) code or in a standalone Portable Executable file that contains only assembly manifest information.
These four items
1 :- assembly name
2 :- version number
3 :- culture
4 :- strong name information
These four make up the assembly's identity.
Assembly name: A string which specifying the assembly's name.
Version number: A major and minor version number, and a revision and build number. The clr uses these numbers to enforce version policy. Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
their individual folders.
Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information.
Satellite Assembly :- An assembly with culture information is automatically assumed to be a satellite assembly.
Strong name information: The public key from the publisher if the assembly has been given a strong name.
List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.
Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.
Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
How to view a Assembly of your code (What is ILDASM ?)

When it comes to understanding of internals nothing can beat ILDASM. ILDASM basically converts the whole exe or dll in to IL code. To run ILDASM you have to go to "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin". Note that i had v2.0 you have to probably change it depending on the type of framework version you have.
If you run IDASM.EXE from the path you will be popped with the IDASM exe program as
shown in figure ILDASM. Click on file and browse to the respective directory for the DLL whose assembly you want to view. After you select the DLL you will be popped with a tree view details of the DLL as shown in figure ILDASM. On double clicking on manifest you will be able to view details of assembly, internal IL code etc as shown in Figure Manifest View.
Note : The version number are in the manifest itself which is defined with the DLL or
EXE thus making deployment much easier as compared to COM where the information
was stored in registry. Note the version information in Figure Manifest view.
You can expand the tree for detail information regarding the DLL like methods etc
How to copy the text from label in window form at run time ?
Designer view:
#region DesignerView
Create a context menu strip :
this.copyPathMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.labelContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyPathMenuItem});
this.labelContextMenuStrip.Name = "labelContextMenuStrip";
this.labelContextMenuStrip.Size = new System.Drawing.Size(100, 22);
this.copyPathMenuItem.Name = "copyPathMenuItem";
this.copyPathMenuItem.Size = new System.Drawing.Size(100, 22);
this.lblSelectedNodePath.ContextMenuStrip = this.labelContextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem copyPathMenuItem;
#endregion
Now handles the label events like :-
private void lblSelectedNodePath_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
copyPathMenuItem.Visible = true;
copyPathMenuItem.Enabled = true;
}
}
Add an click event :-
copyPathMenuItem.Click += new EventHandler(copyPathMenuItem_Click);
Handles the click event :-
private void copyPathMenuItem_Click(object sender, EventArgs e)
{
string labelPath = lblSelectedNodePath.Text.Trim();
if (!string.IsNullOrEmpty(labelPath))
{
Clipboard.SetDataObject(labelPath, false);
}
}
Now you can paste your copy text anywhere Enjoy d Code .....
#region DesignerView
Create a context menu strip :
this.copyPathMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.labelContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyPathMenuItem});
this.labelContextMenuStrip.Name = "labelContextMenuStrip";
this.labelContextMenuStrip.Size = new System.Drawing.Size(100, 22);
this.copyPathMenuItem.Name = "copyPathMenuItem";
this.copyPathMenuItem.Size = new System.Drawing.Size(100, 22);
this.lblSelectedNodePath.ContextMenuStrip = this.labelContextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem copyPathMenuItem;
#endregion
Now handles the label events like :-
private void lblSelectedNodePath_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
copyPathMenuItem.Visible = true;
copyPathMenuItem.Enabled = true;
}
}
Add an click event :-
copyPathMenuItem.Click += new EventHandler(copyPathMenuItem_Click);
Handles the click event :-
private void copyPathMenuItem_Click(object sender, EventArgs e)
{
string labelPath = lblSelectedNodePath.Text.Trim();
if (!string.IsNullOrEmpty(labelPath))
{
Clipboard.SetDataObject(labelPath, false);
}
}
Now you can paste your copy text anywhere Enjoy d Code .....
How can I change the Border color of my control ?
public class MyButton : Button
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int borderWidth = 1;
Color borderColor = Color.Blue;
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, borderColor,
borderWidth, ButtonBorderStyle.Solid, borderColor, borderWidth,
ButtonBorderStyle.Solid, borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid);
}
}
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int borderWidth = 1;
Color borderColor = Color.Blue;
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, borderColor,
borderWidth, ButtonBorderStyle.Solid, borderColor, borderWidth,
ButtonBorderStyle.Solid, borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid);
}
}
How to change the color of Tab Control in c#
Steps :-
1. Set the TabControl's DrawMode to OwnerDraw.
2. Handle the DrawItem event.
private void ChangeColorOFTabControl(object sender, DrawItemEventArgs e)
{
Font TabFont;
Brush BackBrush = new SolidBrush(Color.Green); //Set background color
Brush ForeBrush = new SolidBrush(Color.Yellow);//Set foreground color
if (e.Index == this.tabControl1.SelectedIndex)
{
TabFont = new Font(e.Font, FontStyle.Italic | FontStyle.Bold);
}
else
{
TabFont = e.Font;
}
string TabName = this.tabControl1.TabPages[e.Index].Text;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
e.Graphics.FillRectangle(BackBrush, e.Bounds);
Rectangle r = e.Bounds;
r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
e.Graphics.DrawString(TabName, TabFont, ForeBrush, r, sf);
//Dispose objects
sf.Dispose();
if (e.Index == this.tabControl1.SelectedIndex)
{
TabFont.Dispose();
BackBrush.Dispose();
}
else
{
BackBrush.Dispose();
ForeBrush.Dispose();
}
}
1. Set the TabControl's DrawMode to OwnerDraw.
2. Handle the DrawItem event.
private void ChangeColorOFTabControl(object sender, DrawItemEventArgs e)
{
Font TabFont;
Brush BackBrush = new SolidBrush(Color.Green); //Set background color
Brush ForeBrush = new SolidBrush(Color.Yellow);//Set foreground color
if (e.Index == this.tabControl1.SelectedIndex)
{
TabFont = new Font(e.Font, FontStyle.Italic | FontStyle.Bold);
}
else
{
TabFont = e.Font;
}
string TabName = this.tabControl1.TabPages[e.Index].Text;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
e.Graphics.FillRectangle(BackBrush, e.Bounds);
Rectangle r = e.Bounds;
r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
e.Graphics.DrawString(TabName, TabFont, ForeBrush, r, sf);
//Dispose objects
sf.Dispose();
if (e.Index == this.tabControl1.SelectedIndex)
{
TabFont.Dispose();
BackBrush.Dispose();
}
else
{
BackBrush.Dispose();
ForeBrush.Dispose();
}
}
How to set dropdown width according to longest string in C#
If you are using window control then use this method.
private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
?SystemInformation.VerticalScrollBarWidth:0;
int newWidth;
foreach (string s in ((ComboBox)sender).Items)
{
newWidth = (int) g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth )
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}
If you are a web developer then :-
Get the length of longest string and pass it in unit.pixel method like this :-
DropDownList1.Width = Unit.Pixel(LengthOfTheLongestString)
private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
?SystemInformation.VerticalScrollBarWidth:0;
int newWidth;
foreach (string s in ((ComboBox)sender).Items)
{
newWidth = (int) g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth )
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}
If you are a web developer then :-
Get the length of longest string and pass it in unit.pixel method like this :-
DropDownList1.Width = Unit.Pixel(LengthOfTheLongestString)
How to get the file size like windows file property control ?
//Create an object of FileInfo like :-
FileInfo fileObject = new FileInfo(selectedFilename);
Int64 fileSize = 0;
float sizeOfFile = 0
fileSize = fileObject.Length;
sizeOfFile = fileObject.Length;
private const int FILESIZE_IN_KB = 1024;
public const int FILESIZE_IN_MB = 1048576;
public const int FILESIZE_IN_GB = 1073741824;
public const long FILESIZE_IN_TB = 1099511627776;
private const int START_INDEX = 0;
private const string STRING_VALUE_ZERO = "0";
private const string STRING_VALUE_ONE = "1";
private const string SYMBOL_BYTES = "bytes";
private const string STRING_FORMAT = "n";
public const string FILESIZE_KB = "KB";
private const int FILE_SIZE_LIMIT = 100;
private const string STRING_FORMAT_UPTO_TWO_DECIMAL = ".00";
private const int FILE_SIZE_IN_BYTES = 102400;
private const int FILE_SIZE_IN_MegaBytes = 104857600;
private const long FILE_SIZE_IN_GIGABYTES = 107374182400;
private const string SYMBOL_SPACE = " ";
string size = FormatSize(fileSize,sizeOFFile);
private string FormatSize(Int64 fileSize, float sizeOFFile)
{
//Format number to KB
string stringSize = string.Empty;
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
Int64 fileSizeInKB = 0;
Int64 fileSizeInMB = 0;
long fileSizeInGB = 0;
float fileSizeInKBInFloat = 0;
float fileSizeInMBInFloat = 0;
float fileSizeInGBInFloat = 0;
string byteSize = string.Empty;
if (fileSize < FILESIZE_IN_KB)
{
if (fileSize == 0)
{
//zero byte
stringSize = STRING_VALUE_ZERO + SYMBOL_SPACE + SYMBOL_BYTES;
}
else
{
//less than 1K but not zero byte
stringSize = fileSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + fileSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
}
else if(fileSize < FILESIZE_IN_MB)
{
if (fileSize < FILE_SIZE_IN_BYTES)
{
fileSizeInKBInFloat = (sizeOFFile / (float)FILESIZE_IN_KB);
}
else
{
//convert to KB
fileSizeInKB = (fileSize / FILESIZE_IN_KB);
}
if (fileSizeInKBInFloat != 0)
{
stringSize = fileSizeInKBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInKB.ToString(STRING_FORMAT, numberFormatInfo);
///If file Size is morethan 100 than replace decimal string to emptyString.
if (fileSizeInKB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_DECIMAL, string.Empty);
stringSize = stringSize + "KB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
else if (fileSize < Constants.FILESIZE_IN_GB)
{
if (fileSize < FILE_SIZE_IN_MegaBytes)
{
fileSizeInMBInFloat = (sizeOFFile / (float)FILESIZE_IN_MB);
}
else
{
//convert to KB
fileSizeInMB = (fileSize / FILESIZE_IN_MB);
}
if (fileSizeInMBInFloat != 0)
{
stringSize = fileSizeInMBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInMB.ToString(STRING_FORMAT, numberFormatInfo);
if (fileSizeInMB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
stringSize = stringSize + "MB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize +SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
else if(fileSize < FILESIZE_IN_TB)
{
if (fileSize < FILE_SIZE_IN_GIGABYTES)
{
fileSizeInGBInFloat = (sizeOFFile / (float)FILESIZE_IN_GB);
}
else
{
//convert to KB
fileSizeInGB = (fileSize / FILESIZE_IN_GB);
}
if (fileSizeInGBInFloat != 0)
{
stringSize = fileSizeInGBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInGB.ToString(STRING_FORMAT, numberFormatInfo);
if (fileSizeInGB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
stringSize = stringSize + "GB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
return stringSize;
}
FileInfo fileObject = new FileInfo(selectedFilename);
Int64 fileSize = 0;
float sizeOfFile = 0
fileSize = fileObject.Length;
sizeOfFile = fileObject.Length;
private const int FILESIZE_IN_KB = 1024;
public const int FILESIZE_IN_MB = 1048576;
public const int FILESIZE_IN_GB = 1073741824;
public const long FILESIZE_IN_TB = 1099511627776;
private const int START_INDEX = 0;
private const string STRING_VALUE_ZERO = "0";
private const string STRING_VALUE_ONE = "1";
private const string SYMBOL_BYTES = "bytes";
private const string STRING_FORMAT = "n";
public const string FILESIZE_KB = "KB";
private const int FILE_SIZE_LIMIT = 100;
private const string STRING_FORMAT_UPTO_TWO_DECIMAL = ".00";
private const int FILE_SIZE_IN_BYTES = 102400;
private const int FILE_SIZE_IN_MegaBytes = 104857600;
private const long FILE_SIZE_IN_GIGABYTES = 107374182400;
private const string SYMBOL_SPACE = " ";
string size = FormatSize(fileSize,sizeOFFile);
private string FormatSize(Int64 fileSize, float sizeOFFile)
{
//Format number to KB
string stringSize = string.Empty;
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
Int64 fileSizeInKB = 0;
Int64 fileSizeInMB = 0;
long fileSizeInGB = 0;
float fileSizeInKBInFloat = 0;
float fileSizeInMBInFloat = 0;
float fileSizeInGBInFloat = 0;
string byteSize = string.Empty;
if (fileSize < FILESIZE_IN_KB)
{
if (fileSize == 0)
{
//zero byte
stringSize = STRING_VALUE_ZERO + SYMBOL_SPACE + SYMBOL_BYTES;
}
else
{
//less than 1K but not zero byte
stringSize = fileSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + fileSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
}
else if(fileSize < FILESIZE_IN_MB)
{
if (fileSize < FILE_SIZE_IN_BYTES)
{
fileSizeInKBInFloat = (sizeOFFile / (float)FILESIZE_IN_KB);
}
else
{
//convert to KB
fileSizeInKB = (fileSize / FILESIZE_IN_KB);
}
if (fileSizeInKBInFloat != 0)
{
stringSize = fileSizeInKBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInKB.ToString(STRING_FORMAT, numberFormatInfo);
///If file Size is morethan 100 than replace decimal string to emptyString.
if (fileSizeInKB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_DECIMAL, string.Empty);
stringSize = stringSize + "KB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
else if (fileSize < Constants.FILESIZE_IN_GB)
{
if (fileSize < FILE_SIZE_IN_MegaBytes)
{
fileSizeInMBInFloat = (sizeOFFile / (float)FILESIZE_IN_MB);
}
else
{
//convert to KB
fileSizeInMB = (fileSize / FILESIZE_IN_MB);
}
if (fileSizeInMBInFloat != 0)
{
stringSize = fileSizeInMBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInMB.ToString(STRING_FORMAT, numberFormatInfo);
if (fileSizeInMB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
stringSize = stringSize + "MB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize +SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
else if(fileSize < FILESIZE_IN_TB)
{
if (fileSize < FILE_SIZE_IN_GIGABYTES)
{
fileSizeInGBInFloat = (sizeOFFile / (float)FILESIZE_IN_GB);
}
else
{
//convert to KB
fileSizeInGB = (fileSize / FILESIZE_IN_GB);
}
if (fileSizeInGBInFloat != 0)
{
stringSize = fileSizeInGBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInGB.ToString(STRING_FORMAT, numberFormatInfo);
if (fileSizeInGB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
stringSize = stringSize + "GB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
return stringSize;
}
Sort ListView on column click (like windows folder detail view in xp)




Step :1 Firstly Create the object of listviewcolumn sorter class.
private ListViewColumnSorter listviewColumnSorter=new ListViewColumnSorter();
Step :2 Set ListViewItemSorter property of listView
listView.ListViewItemSorter = listviewColumnSorter;
Handles columnclick event on your form like the above image.
I am pasting the images of listViewItemSorter class please go through it.This class sort the columns according to image,size,text,alphabet.
Get AssociatedFileTypes (.txt = TextDocument)
///
/// Get File Type for given file.
///
/// Pass the path of file
///
This method returns Associated file type like :-
.pdf = Adobe Acrobat Document
.txt = Text Document
private string GetAssociatedFileType(string filePath)
{
private const string STRING_SPACE = " ";
string extension = string.Empty;
if (!string.IsNullOrEmpty(filePath))
{
string extension = Path.GetExtension(filePath);
}
RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension);
while (key != null)
{
string name = (string)key.GetValue(null);
if (name == null)
{
return extension + STRING_SPACE + "File";
}
RegistryKey tempKey = Registry.ClassesRoot.OpenSubKey(name);
if (tempKey == null)
{
return name;
}
key = tempKey;
}
return extension + STRING_SPACE + "File";
}
/// Get File Type for given file.
///
/// Pass the path of file
///
This method returns Associated file type like :-
.pdf = Adobe Acrobat Document
.txt = Text Document
private string GetAssociatedFileType(string filePath)
{
private const string STRING_SPACE = " ";
string extension = string.Empty;
if (!string.IsNullOrEmpty(filePath))
{
string extension = Path.GetExtension(filePath);
}
RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension);
while (key != null)
{
string name = (string)key.GetValue(null);
if (name == null)
{
return extension + STRING_SPACE + "File";
}
RegistryKey tempKey = Registry.ClassesRoot.OpenSubKey(name);
if (tempKey == null)
{
return name;
}
key = tempKey;
}
return extension + STRING_SPACE + "File";
}
File System Watcher in C#(Get notified after any modification)
Drag FileSystemWatcher control in your form from toolbox and add the events for created,deletion and renaming.
Ex:-
#region Designer view
this.fileSystemWatcher.EnableRaisingEvents = true;
this.fileSystemWatcher.IncludeSubdirectories = true;
this.fileSystemWatcher.SynchronizingObject = this;
this.fileSystemWatcher.Created += new System.IO.FileSystemEventHandler(this.fileSystemWatcher_Created);
this.fileSystemWatcher.Deleted += new System.IO.FileSystemEventHandler(this.fileSystemWatcher_Deleted);
this.fileSystemWatcher.Renamed += new System.IO.RenamedEventHandler(this.fileSystemWatcher_Renamed);
public System.IO.FileSystemWatcher fileSystemWatcher;
#endregion
Create three bool variables to set true or false :-
#region Properties
private bool _fileDeleted = false;
private bool _fileRenamed = false;
private bool _fileCreated = false;
public bool FileDeleted
{
set
{
_fileDeleted = value;
}
get
{
return _fileDeleted;
}
}
public bool FileRenamed
{
set
{
_fileRenamed = value;
}
get
{
return _fileRenamed;
}
}
pblic bool FileCreated
{
set
{
_fileCreated = value;
}
get
{
return _fileCreated;
}
}
#endregion
#region EventHandlers
private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
_fileRenamed = true;
MessageBox.Show(e.Name + " Renamed in " + e.FullPath);
}
private void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
_fileDeleted = true;
MessageBox.Show(e.Name + " Deleted in " + e.FullPath);
}
private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
_fileCreated = true;
MessageBox.Show(e.Name + " created in " + e.FullPath);
}
#endregion
By this property if you want to check file has been removed ,deleted from physical path then this will be true and you can check like if you have a tree view and you dont want to repopulate your tree view then use filesystemwatcher and repopulate the tree only when files have been changed,delete or rename. or you can throw a messagebox like above.
Ex:-
#region Designer view
this.fileSystemWatcher.EnableRaisingEvents = true;
this.fileSystemWatcher.IncludeSubdirectories = true;
this.fileSystemWatcher.SynchronizingObject = this;
this.fileSystemWatcher.Created += new System.IO.FileSystemEventHandler(this.fileSystemWatcher_Created);
this.fileSystemWatcher.Deleted += new System.IO.FileSystemEventHandler(this.fileSystemWatcher_Deleted);
this.fileSystemWatcher.Renamed += new System.IO.RenamedEventHandler(this.fileSystemWatcher_Renamed);
public System.IO.FileSystemWatcher fileSystemWatcher;
#endregion
Create three bool variables to set true or false :-
#region Properties
private bool _fileDeleted = false;
private bool _fileRenamed = false;
private bool _fileCreated = false;
public bool FileDeleted
{
set
{
_fileDeleted = value;
}
get
{
return _fileDeleted;
}
}
public bool FileRenamed
{
set
{
_fileRenamed = value;
}
get
{
return _fileRenamed;
}
}
pblic bool FileCreated
{
set
{
_fileCreated = value;
}
get
{
return _fileCreated;
}
}
#endregion
#region EventHandlers
private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
_fileRenamed = true;
MessageBox.Show(e.Name + " Renamed in " + e.FullPath);
}
private void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
_fileDeleted = true;
MessageBox.Show(e.Name + " Deleted in " + e.FullPath);
}
private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
_fileCreated = true;
MessageBox.Show(e.Name + " created in " + e.FullPath);
}
#endregion
By this property if you want to check file has been removed ,deleted from physical path then this will be true and you can check like if you have a tree view and you dont want to repopulate your tree view then use filesystemwatcher and repopulate the tree only when files have been changed,delete or rename. or you can throw a messagebox like above.