ASPNETPROGRAMMINNGUNIT123
ASPNETPROGRAMMINNGUNIT123
(AUTONOMOUS)
SALEM
ACADEMIC YEAR
(2025-2026)
ODD SEMSTER
Paper Title ASP.NET PROGRAMMING
ASP.NET
V CAP05 PROGRAMMING CORE 5 - - 4
Syllabus
E-Content/
Unit Content HOURS Resources
Note:
1.Svetlin Nakov, Veselin Kolev & Co., Fundamentals of Computer
Programming with C#, Faber Publication, 2019.
2. Mathew MacDonald, The Complete Reference ASP.NET, Tata McGraw-
Text Books 1 Hill, 2015.
1 TO 3- Unit I
4 TO 6- Unit II
7 TO 9- Unit III
10 TO 12- Unit IV
13 TO 15- Unit V
16- Unit I
17- Unit II
19- Unit IV
20- Unit V
Components:
CLR (Common Language Runtime): Executes code and provides services like
memory management and security.
FCL (Framework Class Library): Pre-built classes for common functionalities (I/O,
DB access, etc.).
ASP.NET: For building web apps and services.
ADO.NET: For database operations.
Windows Forms / WPF: For desktop applications.
Features:
FCL promotes code reuse, consistency, and productivity, enabling developers to focus on
solving business problems instead of writing low-level code.
C# Fundamentals
Primitive Types and Variables
Primitive Types
Data types are sets (ranges) of values that have similar characteristics.
For instance byte type specifies the set of integers in the range of [0 … 255].
Data types are characterized by:
- Name – for example, int;
- Size (how much memory they use) – for example, 4 bytes;
- Default value – for example 0.
Types
Basic data types in C# are distributed into the following types:
- Integer types – sbyte, byte, short, ushort, int, uint, long, ulong;
- Real floating-point types – float, double;
- Real type with decimal precision – decimal;
- Boolean type – bool;
- Character type – char;
- String – string;
- Object type – object.
These data types are called primitive (built-in types)
because they are embedded in C# language at the lowest level.
The table below represents the above mentioned data types, their range and their default
values:
1. Integer Types
Used for whole numbers (no decimal points).
2. Floating-Point Types
3. Character Type
4. Boolean Type
5. String Type
6. Object Type
object is the base type for all data types in C#.
Any type (value or reference) can be assigned to an object.
object obj = 123;
Variables
A variable is a named storage that holds data which can be used and modified during
program execution.
Syntax:
dataType variableName = value;
A variable is a container of information, which can change its value.
It provides means for:
- storing information
- retrieving the stored information
- modifying the stored information
Naming Variables – Rules
The name of the variable can be any of our choice but must follow certain rules defined in
the C# language specification:
- Variable names can contain the letters a-z, A-Z, the digits 0-9 as well as the character '_'.
- Variable names cannot start with a digit.
- Variable names cannot coincide with a keyword of the C# language.
For example, base, char, default, int, object, this, null and many others cannot be used as
variable names.
Naming Variables – Examples
Proper names:
- name
- first_Name
- _name1
Improper names (will lead to compilation error):
- 1 (digit)
- if (keyword)
- 1name (starts with a digit)
Declaring Variables
When you declare a variable, you perform the following steps:
- specify its type (such as int);
- specify its name (identifier, such as age);
- optionally specify initial value (such as 25) but this is not obligatory.
The syntax for declaring variables in C# is as follows:
<data type> <identifier> [= <initialization>];
Here is an example of declaring variables:
string name;
int age;
Assigning a Value
Assigning a value to a variable is the act of providing a value that must be stored in the
variable.
This operation is performed by the assignment operator "=".
On the left side of the operator we put the variable name and on the right side – its new
value.
Here is an example of assigning values to variables:
name = "John Smith";
age = 25;
Operators
Operators are used to perform operations on variables and values.
Operators in C# can be separated in several different categories:
- Arithmetic operators – they are used to perform simple mathematical
operations.
- Assignment operators – allow assigning values to variables.
- Comparison operators – allow comparison of two literals and/or
variables.
- Logical operators – operators that work with Boolean data types and
Boolean expressions.
- Binary operators – used to perform operations on the binary
representation of numerical data.
- Type conversion operators – allow conversion of data from one type to
another.
1.Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations such as
1. Addition ( + )
2. Subtraction ( - )
3. Multiplication ( * )
4. Division ( / )
5. Modulus ( % )
Example:
// Arithmetic operators
using System;
class Geeks
{
static void Main(string[] args)
{
int x = 8, y = 4;
3. Comparison operators
Comparison operators in C# are used to compare two or more operands.
C# supports the following comparison operators:
- greater than (>)
- less than (<)
- greater than or equal to (>=)
- less than or equal to (<=)
- equality (==)
- difference (!=)
All comparison operators in C# are binary (take two operands) and the returned result is a
Boolean value (true or false).
Comparison operators have lower priority than arithmetical operators but higher than the
assignment operators.
The following example demonstrates the usage of comparison operators in C#:
int x = 10, y = 5;
Console.WriteLine("x > y : " + (x > y)); // True
Console.WriteLine("x < y : " + (x < y)); // False
Console.WriteLine("x >= y : " + (x >= y)); // True
Console.WriteLine("x <= y : " + (x <= y)); // False
Console.WriteLine("x == y : " + (x == y)); // False
Console.WriteLine("x != y : " + (x != y)); // True
4. Logical operators
Logical (Boolean) operators take Boolean values and return a Boolean result (true or
false).
The basic Boolean operators are "AND" (&&), "OR" (||), "exclusive OR" (^) and
logical negation (!).
The following table contains the logical operators in C# and the operations that they
perform:
Example
bool a = true;
bool b = false;
Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(!b); // True
Console.WriteLine(b || true); // True
Console.WriteLine((5 > 7) ^ (a == b)); // False
5.Binary operators
A bitwise operator is an operator that acts on the binary representation of numeric
types.
In computers all the data and particularly numerical data is represented as a series of
ones and zeros.
The binary numeral system is used for this purpose.
For example, number 55 in the binary numeral system is represented as 00110111.
Bitwise operators are very similar to the logical ones.
EXAMPLE
byte a = 3; // 0000 0011 = 3
byte b = 5; // 0000 0101 = 5
Console.WriteLine(a | b); // 0000 0111 = 7
Console.WriteLine(a & b); // 0000 0001 = 1
Console.WriteLine(a ^ b); // 0000 0110 = 6
Console.WriteLine(~a & b); // 0000 0100 = 4
Console.WriteLine(a << 1); // 0000 0110 = 6
Console.WriteLine(a << 2); // 0000 1100 = 12
Console.WriteLine(a >> 1); // 0000 0001 = 1
6. Type conversion operators
Type conversion operators are used to convert a value from one data type to another.
This is also known as type casting.
There are two main types of conversions:
1. Implicit Conversion
2. Explicit Conversion
1. Implicit Conversion
No data loss
Performed automatically by the compiler
Safe conversions (e.g., smaller to larger data types)
Example
int num = 100;
float value = num; // Implicit conversion from int to float
2. Explicit Conversion
Requires manual cast using parentheses
May lose data or cause exceptions
Converts larger type to smaller or incompatible types
Example
double value = 45.78;
int num = (int)value; // Explicit conversion from double to int
Conditional statements
Conditional statements allow your program to make decisions and execute specific blocks of code
based on conditions.
1. if Statement
Executes a block if the condition is true.
Example
int num = 10;
if (num > 5)
{
Console.WriteLine("Number is greater than 5");
}
Output
Number is greater than 5
2. if-else Statement
Executes one block if true, another if false.
Example
int num = 3;
if (num > 5)
{
Console.WriteLine("Greater than 5");
}
else
{
Console.WriteLine("Less than or equal to 5");
}
Output
Less than or equal to 5
4. switch Statement
Used to select one of many blocks of code based on a variable’s value.
Example
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Output
Wednesday
Looping statements
A loop is a basic programming construct that allows repeated execution of a fragment of source
code.
Depending on the type of the loop, the code in it is repeated a fixed number of times or repeats
until a given condition is true (exists).
Loops that never end are called infinite loops.
Using an infinite loop is rarely needed except in cases where somewhere in the body of the loop a
break operator is used to terminate its execution prematurely.
1. While Loops
One of the simplest and most commonly used loops is while.
Checks the condition before the loop starts. Runs as long as the condition is true.
SYNTAX
while (condition)
{
loop body;
}
Example
int i = 1;
while (i <= 5)
{
Console.WriteLine("Count: " + i);
i++;
}
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
2. Do-While Loops
The do-while loop is similar to the while loop, but it checks the condition after each
execution of its loop body.
This type of loops is called loops with condition at the end (post-test loop).
Initially the loop body is executed.
Then its condition is checked. If it is true, the loop‟s body is repeated, otherwise the loop
ends.
This logic is repeated until the condition of the loop is broken.
The body of the loop is executed at least once.
If the loop‟s condition is constantly true, the loop never ends.
SYNTAX
do
{
executable code;
} while (condition);
Example
int i = 1;
do
{
Console.WriteLine("Count: " + i);
i++;
} while (i <= 5);
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
3.For Loops
For-loops are a slightly more complicated than while and do-while loops but on the other
hand they can solve more complicated tasks with less code.
Here is the scheme describing for-loops:
for (int i=0; i<10; i++)
{
/* loop body */
}
They contain an initialization block (A), condition (B), body (D) and updating commands for
the loop variables (C).
We will explain them in details shortly.
Before that, let’s look at how the program code of a for-loop looks like:
for (initialization; condition; update)
{
loop's body;
}
Example
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Count: " + i);
}
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Creating and Using Objects
objects are instances of classes, which are essentially blueprints or templates that define the
properties and behaviors of an object.
Creating Objects
To create an object in C#, you need to:
1. Define a class: A class is a template that defines the properties and methods of an object.
2. Instantiate the class: Use the new keyword to create an instance of the class.
// Define a class
public class Car
{
public string Color { get; set; }
public string Model { get; set; }
// Call methods
myCar.Honk();
Example
using System;
class Program
{
static void Main(string[] args)
{
// Create objects
Car myCar = new Car();
Car yourCar = new Car();
// Set properties
myCar.Color = "Red";
myCar.Model = "Mustang";
yourCar.Color = "Blue";
yourCar.Model = "Camry";
// Call methods
myCar.Honk();
myCar.Describe();
yourCar.Honk();
yourCar.Describe();
}
}
This example defines a Car class with properties and methods, creates two Car objects,
sets their properties, and calls their methods. The output will be:
Output
Beep beep!
This car is a Red Mustang.
Beep beep!
This car is a Blue Camry.
Arrays
Arrays are vital for most programming languages.
They are collections of variables, which we call elements.
An array‟s elements in C# are numbered with 0, 1, 2, … N-1.
Those numbers are called indices. The total number of elements in a given array we
call length of an array.
All elements of a given array are of the same type, no matter whether they are
primitive or reference types.
This allows us to represent a group of similar elements as an ordered sequence and
work on them as a whole.
Arrays can be in different dimensions, but the most used are the one dimensional and
the two-dimensional arrays.
One-dimensional arrays are also called vectors and two-dimensional are also known
as matrices.
Declaration and Allocation of Memory for Arrays
Declaring an Array
We declare an array in C# in the following way:
int[] myArray;
In this example the variable myArray is the name of the array, which is of integer type
(int[]).
Creation of an Array – the Operator "new"
In C# we create an array with the help of the keyword new, which is used to allocate memory:
int[] myArray = new int[6];
In this example we allocate an array with length of 6 elements of type int.
This means that in the dynamic memory (heap) an area of 6 integer numbers is allocated and
they all are initialized with the value 0:
Stack Heap myArray Stack H
With this syntax we use curly brackets instead of the operator new.
Between the brackets we list the initial values of the array, separated by commas.
Their count defines the length of the array.
Declaration and Initialization of an Array – Example
Here is one more example how to declare and initialize an array:
string[] daysOfWeek =
{ "Monday", "Tuesday", "Wednesday","Thursday", "Friday",
"Saturday", "Sunday" };
Boundaries of an Array
Arrays are by default zero-based, which means the enumeration of the elements starts from 0.
The first element has the index 0, the second – 1, etc. In an array of N elements, the last element
has the index N-1
Access to the Elements of an Array
We access the array elements directly using their indices.
Each element can be accessed through the name of the array and the element‟s index
(consecutive number) placed in the brackets.
We can access given elements of the array both for reading and for writing, which
means we can treat elements as variables.
Here is an example for accessing an element of an array:
myArray[index] = 100;
In the example above we set a value of 100 to the element, which is at position index.
String operations
String operations in C# are used to manipulate and analyze strings. Here are some
common string operations
1. Concatenation
You can concatenate strings using the + operator or the string.Concat() method.
Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
Output: John Doe
2. String Interpolation
String interpolation allows you to embed expressions within string literals. Use
the $ symbol before the string
Example
string name = "John";
int age = 30;
string message = $"My name is {name} and I am {age} years old.";
Console.WriteLine(message);
Output: My name is John and I am 30 years old.
3. String Comparison
You can compare strings using the == operator, string.Equals() method,
or string.Compare() method.
Example
string str1 = “Hello”;
string str2 = “hello”;
bool isEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isEqual);
Output: True
4. Substring
You can extract a substring from a string using the Substring() method.
Example
string str = “Hello World”;
string substr = str.Substring(6);
Console.WriteLine(substr);
Output: World
5. Split
You can split a string into an array of substrings using the Split() method.
Example
string str = “apple,banana,orange”;
string[] fruits = str.Split(„,‟);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Output:
apple
banana
orange
6. Trim
You can remove whitespace characters from the beginning and end of a string using
the Trim() method.
Example
string str = “ Hello World “;
string trimmedStr = str.Trim();
Console.WriteLine(trimmedStr);
Output: Hello World
7. Replace
You can replace a substring with another string using the Replace() method.
Example
string str = “Hello World”;
string newStr = str.Replace(“World”, “Universe”);
Console.WriteLine(newStr);
Output: Hello Universe
8. Contains
You can check if a string contains a substring using the Contains() method.
Example
string str = “Hello World”;
bool contains = str.Contains(“World”);
Console.WriteLine(contains);
Output: True
9. IndexOf
You can find the index of a substring within a string using the IndexOf() method.
Example
string str = “Hello World”;
int index = str.IndexOf(“World”);
Console.WriteLine(index);
Output: 6
10. ToUpper and ToLower
You can convert a string to uppercase or lowercase using
the ToUpper() and ToLower() methods.
Example
string str = “Hello World”;
string upperStr = str.ToUpper();
string lowerStr = str.ToLower();
Console.WriteLine(upperStr);
Console.WriteLine(lowerStr);
Output: HELLO WORLD
Output: hello world
ONE MARKS
1.What is the primary function of the Common Language Runtime (CLR) in the .NET
Framework?
a) To provide a set of pre-built classes for common tasks
b) To manage the execution of .NET applications
c) To compile C# code into machine code
d) To provide a user interface for .NET applications
Answer: b) To manage the execution of .NET applications
2.What is the Framework Class Library (FCL) in the .NET Framework?
a) A set of classes for building Windows Forms applications
b) A set of classes for building web applications
c) A comprehensive set of pre-built classes for common tasks
d) A set of classes for building console applications
Answer: c) A comprehensive set of pre-built classes for common tasks
3.Which of the following is a primitive type in C#?
a) string
b) int
c) Array
d) List<T>
Answer: b) int
4.What is the purpose of the var keyword in C#?
a) To declare a variable with a specific type
b) To declare a variable without specifying its type
c) To declare a constant variable
d) To declare a static variable
Answer: b) To declare a variable without specifying its type
5.What is the difference between the == operator and the Equals() method in C#?
a) == checks for reference equality, while Equals() checks for value equality
b) == checks for value equality, while Equals() checks for reference equality
c) == is used for strings, while Equals() is used for numbers
d) == is used for numbers, while Equals() is used for strings
Answer: a) == checks for reference equality, while Equals() checks for value equality
(although == can be overloaded to check for value equality)
6.What is the purpose of the switch statement in C#?
a) To execute a block of code repeatedly
b) To execute a block of code conditionally
c) To execute different blocks of code based on a specific value
d) To declare a variable
Answer: c) To execute different blocks of code based on a specific value
7.What is the difference between a while loop and a do-while loop in C#?
a) A while loop executes the code block at least once, while a do-while loop may not execute
the code block at all
b) A do-while loop executes the code block at least once, while a while loop may not execute
the code block at all
c) A while loop is used for arrays, while a do-while loop is used for lists
d) A while loop is used for numbers, while a do-while loop is used for strings
Answer: b) A do-while loop executes the code block at least once, while a while loop may
not execute the code block at all
8.What is the purpose of the new keyword in C#?
a) To declare a variable
b) To create an instance of a class
c) To call a method
d) To access a property
Answer: b) To create an instance of a class
9.How do you access a property of an object in C#?
a) Using the dot notation (e.g., obj.Property)
b) Using the bracket notation (e.g., obj["Property"])
c) Using the GetProperty() method
d) Using the SetProperty() method
Answer: a) Using the dot notation (e.g., obj.Property)
10.How do you declare an array in C#?
a) int[] arr = new int[5];
b) int arr = new int[5];
c) int[] arr = new int();
d) int arr = new int();
Answer: a) int[] arr = new int[5];
11.How do you access an element of an array in C#?
a) Using the dot notation (e.g., arr.0)
b) Using the bracket notation (e.g., arr[0])
c) Using the GetElement() method
d) Using the SetElement() method
Answer: b) Using the bracket notation (e.g., arr[0])
12.How do you concatenate two strings in C#?
a) Using the + operator
b) Using the Concat() method
c) Using the Join() method
d) Using the Split() method
Answer: a) Using the + operator (or b) Using the Concat() method)
13.How do you compare two strings in C#?
a) Using the == operator
b) Using the Equals() method
c) Using the Compare() method
d) Using the CompareTo() method
Answer: a) Using the == operator (or b) Using the Equals() method)
14. What is the purpose of the if-else statement in C#?
a) To execute a block of code repeatedly
b) To execute a block of code conditionally
c) To exit a loop or switch statement
d) To return a value from a method
Answer: b) To execute a block of code conditionally
15.What is the purpose of the switch statement in C#?
a) To execute a block of code repeatedly
b) To execute a block of code conditionally
c) To execute different blocks of code based on a specific value
d) To return a value from a method
Answer: c) To execute different blocks of code based on a specific value
5 MARKS
1.Explain about the Common Language Runtime.
2.what is variable? Explain about declaring and accessing variable in C#.
3.How to create a object in C#?
4.explain about string manipulation?
10MARKS
1.Discuss about the C# primitive data types in detail.
2.Explain about the operators in C#.
3.Discuss about the C# conditional statements.
4.What is loops in C#?Explain in detail.
5.Explain about arrays in C#.
6.Discuss about string manipulation in C#.
********UNIT-1********
UNIT-2
HTML controls
In ASP.NET, HTML controls refer to standard HTML elements that can be used on web
pages.
These controls can be used to create user interfaces, collect user input, and interact with
users.
Types of HTML Controls in ASP.NET:
1. HTML Server Controls: These are HTML elements that are converted to server controls,
allowing them to be accessed and manipulated on the server-side.
2. HTML Client Controls: These are standard HTML elements that run on the client-side (in
the browser).
Common HTML Controls in ASP.NET:
1. Text Box: <input type="text">
2. Button: <input type="button"> or <button>
3. CheckBox: <input type="checkbox">
4. RadioButton: <input type="radio">
5. Drop Down List: <select>
6. Text Area: <textarea>
Using HTML Controls in ASP.NET:
1. Add HTML elements to a web page: Use standard HTML syntax to add elements to
a web page.
2. Add runat="server" attribute: To make an HTML element a server control, add the
runat="server" attribute.
3. Access controls on the server-side: Use the control's ID to access and manipulate it
on the server-side.
ONE MARKS
1.What is ASP.NET?
a) A client-side scripting language
b) A server-side web development framework
c) A database management system
d) A web server
Answer: b) A server-side web development framework
2.What is the primary purpose of ASP.NET?
a) To create desktop applications
b) To create web applications
c) To create mobile applications
d) To create games
Answer: b) To create web applications
3.What is the most commonly used IDE for ASP.NET development?
a) Visual Studio
b) Eclipse
c) NetBeans
d) IntelliJ IDEA
Answer: a) Visual Studio
4.What is the purpose of an IDE in ASP.NET development?
a) To write code
b) To design web pages
c) To debug applications
d) All of the above
Answer: d) All of the above
5.Which of the following languages are supported by ASP.NET?
a) C#
b) VB.NET
c) F#
d) All of the above
Answer: d) All of the above
6.What is a component in ASP.NET?
a) A reusable piece of code
b) A web page
c) A database table
d) A web server
Answer: a) A reusable piece of code
7.What is an example of a component in ASP.NET?
a) A web control
b) A class library
c) A web service
d) All of the above
Answer: d) All of the above
8.What is a Web Form in ASP.NET?
a) A web page that uses server-side controls
b) A web page that uses client-side scripting
c) A web page that uses a database
d) A web page that uses a web service
Answer: a) A web page that uses server-side controls
9.How do you create a new Web Form in ASP.NET?
a) By adding a new item to a project
b) By creating a new project
c) By copying an existing Web Form
d) By using a template
Answer: a) By adding a new item to a project
10.What is a standard control in ASP.NET?
a) A control that is included in the .NET Framework
b) A control that is created by a developer
c) A control that is used for data binding
d) A control that is used for validation
Answer: a) A control that is included in the .NET Framework
11.What are some examples of standard controls in ASP.NET?
a) Button, TextBox, Label
b) GridView, DetailsView, FormView
c) Menu, TreeView, SiteMapPath
d) All of the above
Answer: d) All of the above
12.What is a property of a control in ASP.NET?
a) A characteristic of the control
b) An action that the control can perform
c) A method that the control can call
d) An event that the control can raise
Answer: a) A characteristic of the control
13.What is an event of a control in ASP.NET?
a) A characteristic of the control
b) An action that the control can perform
c) A notification that something has happened
d) A method that the control can call
Answer: c) A notification that something has happened
14.What is an HTML control in ASP.NET?
a) A server-side control
b) A client-side control
c) A control that is used for data binding
d) A control that is used for validation
Answer: b) A client-side control
15.How do you add an HTML control to a Web Form?
a) By dragging and dropping the control from the toolbox
b) By writing HTML code
c) By using a server-side control
d) By using a third-party control
Answer: b) By writing HTML code
5 MARKS
1. What are the benefits of using ASP.NET for web development?
2. How do you create a new ASP.NET project in Visual Studio?
3. What is a Web Form in ASP.NET?
4. How do you create a new Web Form in ASP.NET?
5. What are some examples of standard controls in ASP.NET?
6. What are the benefits of using HTML controls?
10 MARKS
1.Explain about the IDE in ASP.NET.
2.Discuss about working with web forms in asp.net.
3.What are the basic standard controls in web forms?
4.explain about the list controls and its properties.
********UNIT-2********
UNIT-3
Rich Controls & Validation Controls
Rich Controls: Properties and its events
Rich Controls, also known as Rich Text Boxes or Rich Edit controls, are graphical user
interface components that allow users to edit and format text with various styles, colors, and
fonts.
Properties:
1. Text: The text content of the control.
2. Font: The font family, size, and style (e.g., bold, italic) applied to the text.
3. ForeColor and BackColor: The text color and background color of the control.
4. Selection: The currently selected text or the position of the caret.
5. Multiline: A property that determines whether the control can display multiple lines of
text.
Events:
1. TextChanged: Fired when the text content of the control changes.
2. SelectionChanged: Fired when the selection or caret position changes.
3. LinkClicked: Fired when a link in the control is clicked (if the control supports links).
4. ContentsResized: Fired when the content size changes, such as when text is added or
removed.
These properties and events enable developers to customize the behavior and appearance of
Rich Controls, making them suitable for various applications, such as text editors, chat
interfaces, or report generators.
class FileStreamExample
{
public static void Main()
{
// Create a FileStream
using (FileStream fs = new FileStream("example.txt", FileMode.Create))
{
// Write to the file
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello, World!");
}
}
File Share
File sharing is the process of sharing files between different users or systems over a
network. In ASP.NET, file sharing can be implemented by uploading files to a server and
allowing other users to download them.
Example:
Suppose we have an ASP.NET web application where users can upload and share files.
Here's a basic example:
1. Upload File:
User selects a file using a file upload control.
The file is uploaded to the server and stored in a designated folder.
2. Share File:
The uploaded file is listed on a webpage with a download link.
Other users can click on the download link to download the file.
Reading and Writing to files
C# provides several classes for reading and writing to files, including:
1. File: Provides static methods for reading and writing to files.
2. FileStream: Provides a stream for reading and writing to files.
3. StreamReader: Provides a reader for reading text from a file.
4. StreamWriter: Provides a writer for writing text to a file.
Reading from a File
Using File.ReadAllText():
string filePath = "example.txt";
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);
Using StreamReader:
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string fileContent = reader.ReadToEnd();
Console.WriteLine(fileContent);
}
Writing to a File
Using File.WriteAllText():
string filePath = "example.txt";
string fileContent = "Hello, World!";
File.WriteAllText(filePath, fileContent);
Using StreamWriter:
string filePath = "example.txt";
string fileContent = "Hello, World!";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(fileContent);
}
Reading and Writing to a File Line by Line
Using File.ReadAllLines():
string filePath = "example.txt";
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
Using StreamReader:
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Common File Modes
1. FileMode.Create: Creates a new file or overwrites an existing one.
2. FileMode.Append: Appends to an existing file or creates a new one if it doesn't exist.
3. FileMode.Open: Opens an existing file.
4. FileMode.OpenOrCreate: Opens an existing file or creates a new one if it doesn't
exist.
File Access
1. FileAccess.Read: Allows reading from a file.
2. FileAccess.Write: Allows writing to a file.
3. FileAccess.ReadWrite: Allows both reading and writing to a file.
1. Check for file existence: Verify that a file exists before attempting to move, copy, or
delete it.
2. Handle exceptions: Catch and handle exceptions that may occur during file
operations.
3. Use try-catch blocks: Ensure that file operations are wrapped in try-catch blocks to
handle potential errors.
FileInfo Class
The FileInfo class provides instance methods for performing file operations. Here's an example:
Example
FileInfo fileInfo = new FileInfo("example.txt");
if (fileInfo.Exists)
{
fileInfo.CopyTo("destination.txt");
fileInfo.MoveTo("newLocation.txt");
fileInfo.Delete();
}
Common File Operations Exceptions
1. FileNotFoundException: Thrown when a file is not found.
2. IOException: Thrown when an I/O error occurs.
3. UnauthorizedAccessException: Thrown when access to a file is denied.
File uploading
File uploading is a common feature in web applications that allows users to upload files to
the server.
Here's an example of how to implement file uploading in ASP.NET:
ASPX Page
Aspx
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"
/>
<asp:Label ID="lblStatus" runat="server" Text="" />
Code-Behind C#
5 MARKS
1. Explain the different file modes available in .NET, such as Create, Append, Open, and
OpenOrCreate. Provide examples.
2. Explain how to use the FileUpload control in ASP.NET to upload files. Provide an example.
3.How do you validate the file type and size of an uploaded file?
4.How do you create a new file using the File.Create method? Provide an example.
10 MARKS
1.Explain about rich controls and its properties in detail.
2. Explain about validation controls and its properties in detail.
3.How to share files explain in detail?
4. Explain the different file modes available in .NET, such as Create, Append, Open, and Open Or
Create. Provide examples
5.how to read and write to a file?
********UNIT-3********