Hi,
For uploading files to server using the new FileUpload control in C#,
<%@ Page Language="C#"%>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
try {
FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex) {
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>FileUpload Server Control</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" Runat="server" />
<asp:Button ID="Button1" Runat="server" Text="Upload"
OnClick="Button1_Click" />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</form>
</body>
</html>
Hi,
For uploading files to server in C#/C Sharp,
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UploadFile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="Uploader" runat="server" Height="24px" Width="472px" />
<asp:Button ID="cmdUpload" runat="server" Height="24px" OnClick="cmdUpload_Click"
Text="Upload" Width="88px" /><br />
<br />
<asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-Bold="True"></asp:Label></div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class UploadFile : System.Web.UI.Page
{
private string uploadDirectory;
protected void Page_Load(object sender, EventArgs e)
{
uploadDirectory = Path.Combine(Request.PhysicalApplicationPath, "Uploads");
}
protected void cmdUpload_Click(object sender, EventArgs e)
{
if (Uploader.PostedFile.FileName == "")
{
lblInfo.Text = "No file specified.";
}
else
{
string extension = Path.GetExtension(Uploader.PostedFile.FileName);
switch (extension.ToLower())
{
case ".png":
case ".jpg":
break;
default:
lblInfo.Text = "This file type is not allowed.";
return;
}
string serverFileName = Path.GetFileName(Uploader.PostedFile.FileName);
string fullUploadPath = Path.Combine(uploadDirectory,serverFileName);
try
{
Uploader.PostedFile.SaveAs(fullUploadPath);
lblInfo.Text = "File " + serverFileName;
lblInfo.Text += " uploaded successfully to ";
lblInfo.Text += fullUploadPath;
}
catch (Exception err)
{
lblInfo.Text = err.Message;
}
}
}
}
Hi,
Use the following simple lines of code to check whether a particular file exists or not using C#/C Sharp.
using System;
using System.IO;
static class MainClass
{
static void Main(string[] args)
{
Console.WriteLine(File.Exists("c:yourFile.txt"));
}
}
It will return either True or False depending on whether your file exists or not.
Hi,
Sometimes you may need to convert string to double using C#, see the following lines of code to see how you could do it.
class MainClass
{
static void Main()
{
string myString = " 3.14159";
double myValue= System.Convert.ToDouble(myString );
}
}
Hi,
Sometimes you may need to get all the characters in a string using C Sharp/C#. The following code gives you an example of how to get or display all the characters of a given string.
using System;
class MainClass
{
public static void Main()
{
string sampleString= "I Love Coding";
for (int num = 0; num < sampleString.Length; num++)
{
Console.WriteLine("sampleString[" + num + "] = " + sampleString[num]);
}
}
}
Output:
sampleString[0] = I
sampleString[1] =
sampleString[2] = L
sampleString[3] = o
sampleString[4] = v
sampleString[5] = e
sampleString[6] =
sampleString[7] = C
sampleString[8] = o
sampleString[9] = d
sampleString[10] = i
sampleString[11] = n
sampleString[12] = g
Hi,
Use the following code if you want to reverse the digits of a number using C Sharp/C #.
using System;
class MainClass {
public static void Main() {
int urNum;
int urdigits;
urNum = 123;
Console.WriteLine("Given Number: " + urNum);
Console.Write("Reversed Number: ");
do {
urdigits = urNum % 10;
Console.Write(urdigits);
urNum = urNum / 10;
} while(urNum > 0);
Console.WriteLine();
}
}
Output :
Given Number: 123
Reversed Number: 321
Hi,
Use the following simple lines of code to check whether a particular file exists or not using C#/C Sharp.
using System;
using System.IO;
static class MainClass
{
static void Main(string[] args)
{
Console.WriteLine(File.Exists("c:yourFile.txt"));
}
}
It will return either True or False depending on whether your file exists or not.
Hi,
For replacing a substring in C Sharp/C#, use the following lines of code.
using System;
class Class1
{
static void Main(string[] args)
{
string newStr = "Heaven";
string finalStr = "CoderzWorld";
finalStr = finalStr.Replace( "World", newStr);
Console.WriteLine( finalStr);
}
}
Hi,
In order to sort the elements in a string array in C Sharp/C#, we use the sort() method. Given below is a simple example using sort() method to sort the elements in a string array.
using System;
class MainClass
{
public static void Main()
{
string[] urStringArray = {"xylo", "apple", "zeebra", "coderz", "heaven123", "heaven777"};
Array.Sort(urStringArray );
Console.WriteLine("Sorted string Array:");
for (int i = 0; i < urStringArray.Length; i++)
{
Console.WriteLine("urStringArray[" + i + "] = " + urStringArray[i]);
}
}
}
It will print out,
Sorted string Array:
urStringArray[0] = apple
urStringArray[1] = coderz
urStringArray[2] = heaven123
urStringArray[3] = heaven777
urStringArray[4] = xylo
urStringArray[5] = zeebra
Hi,
As you know an exception is an error that occurs during the runtime.
Here is a simple exception handling example using C Sharp/C#.
using System;
class MainClass{
public static void Main(){
int value= 0;
try {
int i = 7/value;
}
catch (DivideByZeroException e) // catching divide by zero exception
{
Console.WriteLine("DivideByZero {0}", e);
}
catch (Exception e) // catching any other exceptions
{
Console.WriteLine("Exception {0}", e);
}
}
}
Hi,
This is how you can simply rename a namespace in C Sharp/C#,
using urNamedClass = System.Console;
class MainClass
{
public static void Main()
{
urNamedClass.WriteLine("Hello");
}
}
This will print out ‘Hello’!
Hi,
Given below is an example of a C#/C Sharp Random Access File.
using System;
using System.IO;
class MainClass {
public static void Main() {
FileStream alphaStr;
char alphaChr;
try {
alphaStr = new FileStream("randomDatFile.dat", FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return ;
}
// Write the alphabet.
for(int i=0; i < 26; i++) {
try {
alphaStr.WriteByte((byte)('A'+i));
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return ;
}
}
try {
alphaStr.Seek(0, SeekOrigin.Begin); // seeking first
alphaChr = (char) f.ReadByte();
Console.WriteLine("First value is " + alphaChr);
alphaStr.Seek(1, SeekOrigin.Begin); // seeking second
alphaChr = (char) f.ReadByte();
Console.WriteLine("Second value is " + alphaChr);
alphaStr.Seek(25, SeekOrigin.Begin); // seeking 26th
alphaChr = (char) f.ReadByte();
Console.WriteLine("Last value is " + alphaChr);
Console.WriteLine();
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
}
Console.WriteLine();
alphaStr.Close();
}
}
And the output will be…
First value is A
Second value is B
Last value is E
This example shows how you can randomly access data.
Hi,
Sometimes you need to check for whether the given string is Palindrome or not. Given below is a sample code to check whether the given string is Palindrome or not using C Sharp/C#.
class Palindrome
{
static void Main()
{
string checkStr, sampleStr;
char[] temp;
System.Console.Write("Enter your String: ");
sampleStr = System.Console.ReadLine();
checkStr = sampleStr.Replace(" ", "");
checkStr = checkStr.ToLower();
temp = checkStr.ToCharArray();
System.Array.Reverse(temp);
if(checkStr== new string(temp))
{
System.Console.WriteLine(""{0}" is a palindrome.",sampleStr);
}
else
{
System.Console.WriteLine(""{0}" is NOT a palindrome.",sampleStr);
}
}
}
Hi,
We have discussed here copying a file using FileInfo. Now we are going to see how we can do the same without using FileInfo in C Sharp/C#.
using System;
using System.IO;
class MainClass {
public static void Main(string[] args) {
int i;
FileStream fileIn;
FileStream fileOut;
try {
fileIn = new FileStream("opFile.txt", FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message + "nFile Not Found");
return;
}
try {
fileOut = new FileStream("clFile.txt", FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "nError Opening File");
return;
}
try {
do {
i = fileIn.ReadByte();
if(i != -1)
fileOut.WriteByte((byte)i);
} while(i != -1);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "Error");
}
fileIn.Close();
fileOut.Close();
}
}
Hi,
For copying a file using FileInfo in C Sharp/C#, use the following code. For copying a file without using file info check the example given here.
using System;
using System.IO;
public class MainClass
{
static void Main(string[] args)
{
FileInfo testFile = new FileInfo(@"c:NewWorkstestOld.txt");
testFile.Create();
testFile.CopyTo(@"c:NewProjtestNew.txt");
}
}
Hi,
Use the following code example to read a complete text file using C Sharp/C#.
using System;
using System.Data;
using System.IO;
class Class1{
static void Main(string[] args){
StreamReader sampleStreaming= new StreamReader("trialText.txt");
Console.WriteLine(sampleStreaming.ReadToEnd());
sampleStreaming.Close();
}
}
Hi,
Use the following example code, if you want to write to a text file using C Sharp/C#.
using System;
using System.IO;
class MainClass
{
public static void Main()
{
FileStream trialStream = new FileStream("sampleText.txt", FileMode.Create);
StreamWriter trialWrite = new StreamWriter(trialStream );
trialWrite.WriteLine("{0} {1}", "CoderzHeaven", 100);
trialWrite.Close();
trialStream .Close();
}
}
Hi,
It will be very useful to know how you can convert a given string into uppercase or lowercase using program.
We are going to show you , how to convert a given string into uppercase or lowercase using C Sharp/C#. See the example given below.
using System;
class MainClass {
public static void Main() {
string sampleString = "CoDeRzHeAvEn";
string strLwrCase = sampleString .ToLower();
string strUprCase = sampleString .ToUpper();
Console.WriteLine("Lowercase of sampleString :n " + strLwrCase );
Console.WriteLine("Uppercase of sampleString :n " + strUprCase );
}
}
Output :
Lowercase of sampleString :
coderzheaven
Uppercase of sampleString :
CODERZHEAVEN
Hi,
Sometimes you may need to check whether two strings are equal or not equal by checking case insensitive. See the example below to see how to achieve the same using C Sharp /C#.
using System;
class MainClass {
public static void Main() {
string strOne = "heaven";
string strTwo = "HEAVEN";
if(String.Compare(strOne , strTwo , true) == 0)
Console.WriteLine(strOne + " and " + strTwo + " are equal - Case Insensitive!");
else
Console.WriteLine(strOne + " and " + strTwo + " are not equal - Case Insensitive!");
}
}
Output : heaven and HEAVEN are equal – Case Insensitive!
Hi,
Here is a simple program to generate Fibonacci series using C Sharp /C#. It will generate Fibonacci numbers < 100.
class MainClass
{
public static void Main()
{
int oldNum = 1;
int presentNum = 1;
int nextNum;
System.Console.Write(presentNum + ",");
while (presentNum < 100)
{
System.Console.Write(presentNum + ",");
nextNum = presentNum + oldNum;
oldNum = presentNum;
presentNum = nextNum;
}
}
}
Hi,
Sometimes you may need to get the files from a specified directory using C# / C Sharp. See the sample code on how it works.
using System;
using System.IO;
class MainClass
{
public static void Main()
{
string[] yourFiles = Directory.GetFiles("c:");
foreach (string fNames in yourFiles)
Console.WriteLine(fNames);
}
}
This code will get you files from the root directory.
Hi,
Let’s see a simple example of deleting a file in a folder using c#.
using System;
using System.IO;
public class MainClass
{
static void Main(string[] args)
{
FileInfo sampleFile= new FileInfo(@"c:SamplestestFile.txt");
sampleFile.Create();
sampleFile.Delete();
}
}
sampleFile.Create() will create the file in the specified folder.
sampleFile.Delete() will delete the file in the specified folder.
Hi,
How can you create a text file in C# and write to it? Sometimes you may need to create a text file using C sharp program. Here is how you can do that.
using System;
using System.IO;
class MainClass
{
static void Main(string[] args)
{
StreamWriter yourStream= null;
string yourString= "I Love Coderz Heaven!";
try
{
yourStream = File.CreateText("testFile.txt");
yourStream.Write(yourString);
}
catch (IOException e)
{
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (yourStream!= null)
{
yourStream.Close();
}
}
}
}
Hi,
See how a very simple exception handling works with try-catch methods using C#.
using System;
class MainClass{
public static void Main(){
int divOne = 0;
try {
int ans = 79 / divOne ;
}
catch (Exception e) {
Console.WriteLine("You got the exception-> " + e.Message);
}
}
}
Output- “You got the exception-> Attempted to divide by zero.”
Hi,
Sometimes you may need to find whether a particular year is leap year or not. But how can you find out whether a particular year is leap year or not in C# ? Use the following code.
using System;
class MainClass
{
public static void Main()
{
bool myResult= DateTime.IsLeapYear(2011);
Console.WriteLine("Is the year 2011 a leap year ? = " + myResult);
}
}
And the output is,
Is the year 2011 a leap year ? = False