This blog is about the dotnet.all types of codes,news about dotnet including asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.ncluding asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.asp.net programming,dot net programming,dotnet programs,dotnet source code,source code.

Free Hosting

Free Hosting

Saturday, November 29, 2008

Constructor vs Static Constructor in c#(CSharp)

A Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members. Here I am just talking about the Constructors. How they get initialized and how they behave.

Things to know about Static Constructor

It is used to initialize static data members.

Can't access anything but static members.

Can't have parameters

Can't have access modifiers like Public, Private or Protected.
Now once you understand the above points, you can appreciate the difference between Static Class and Unstatic Class

Static Class cannot be instantiated unlike the unstatic class. You should directly access its Method via the ClassName.MethodName

A Program can't tell when it is going to load static class but its definitely loaded before the call.

A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.

A Static class can contain only static members. So all the members and functions have to be static.

A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)
Let's look at a normal Constructor

class Program
{
static void Main(string[] args)
{


/* Note two things

1.Here you get to instantiate the Constructor in the code wherever you like.

2.If you debug you get to goto the Constructor and see what is being done.

*/
MyExample myExample = new MyExample();
myExample.Print();
}
}

public class MyExample
{
private static int StaticVariable ;
public MyExample()
{
if (StaticVariable < 10)
{
StaticVariable = 20;
}
else
{
StaticVariable = 100;
}
}


public void Print()
{
Console.WriteLine(StaticVariable);
}
}



Now consider this second example for static class

class Program
{
static void Main(string[] args)
{


/* Note the following

1.You dont get to instantiate for sure so you dont know when the constructor was called.

2.Secondly you can access your method directly.

*/

//MyExampleStatic myExampleStatic = new MyExampleStatic();
MyExampleStatic.Print();
}
}


static class MyExampleStatic
{
private static int StaticVariable;
static MyExampleStatic()
{
if (StaticVariable < 10)
{
StaticVariable = 20;
}
else
{
StaticVariable = 100;
}
}
public static void Print()
{
Console.WriteLine(StaticVariable);
}
}


The point is that static member could be used only by a static Constructor or static Function. Hope you have a Static Constructing life.

Delegates in C# (Csharp)

delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

A delegate type maintains three important pices of information :

The name of the method on which it make calls.

Any argument (if any) of this method.

The return value (if any) of this method.

Defining a Delegate in C#

when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer.

public delegate int DelegateName(int x, int y);

A Delegate Usage Example

namespace MyFirstDelegate

{

//This delegate can point to any method,

//taking two integers and returning an

//integer.

public delegate int MyDelegate(int x, int y);

//This class contains methods that MyDelegate will point to.

public class MyClass

{

public static int Add(int x, int y)

{

return x + y;

}

public static int Multiply(int x, int y)

{

return x * y;

}

}

class Program

{

static void Main(string[] args)

{

//Create an Instance of MyDelegate

//that points to MyClass.Add().

MyDelegate del1 = new MyDelegate(MyClass.Add);

//Invoke Add() method using the delegate.

int addResult = del1(5, 5);

Console.WriteLine("5 + 5 = {0}\n", addResult);

//Create an Instance of MyDelegate

//that points to MyClass.Multiply().

MyDelegate del2 = new MyDelegate(MyClass.Multiply);

//Invoke Multiply() method using the delegate.

int multiplyResult = del2(5, 5);

Console.WriteLine("5 X 5 = {0}", multiplyResult);

Console.ReadLine();

}

}
}


Delegate ability to Multicast

Delegate's ability to multicast means that a delegate object can maintain a list of methods to call, rather than a single method
if you want to add a method to the invocation list of a delegate object , you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -= .

Note: The Multicast delegate here contain methods that return void, if you want to create a multicast delegate with return type you will get the return type of the last method in the invocation list.


A Multicast Delegate Example


namespace MyMulticastDelegate

{

//this delegate will be used to call more than one

//method at once

public delegate void MulticastDelegate(int x, int y);

//This class contains methods that MyDelegate will point to.

public class MyClass

{

public static void Add(int x, int y)

{

Console.WriteLine("You are in Add() Method");

Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);

}

public static void Multiply(int x, int y)

{

Console.WriteLine("You are in Multiply() Method");

Console.WriteLine("{0} X {1} = {2}", x, y, x * y);

}

}

class Program

{

static void Main(string[] args)

{

//Create an Instance of MulticastDelegate

//that points to MyClass.Add().

MulticastDelegate del = new MulticastDelegate(MyClass.Add);

//using the same instance of MulticastDelegate

//to call MyClass.Multibly() by adding it to it's

//invocation list.

del += new MulticastDelegate(MyClass.Multiply);

//Invoke Add() and Multiply() methods using the delegate.

//Note that these methods must have a void return vlue

Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");

del(5, 5);



//removing the Add() method from the invocation list

del -= new MulticastDelegate(MyClass.Add);

Console.WriteLine("\n\n****Add() Method removed.****\n\n");

//this will invoke the Multibly() method only.

del(5, 5);

}

}

}


Delegate Covariance

Assume you are designing a delegate that can point to methods returning a custom class type:

//Define a delegate pointing to methods returning Employee types.

public delegate Employee EmployeeDelegate();

if you were to derive a new class from Employee Type named SalesEmployee and wish to create a delegate type that can point to methods returning this class type you would be required to define an entirely new delegate to do so


//a new delegate pointing to methods returning SalesEmployee types.

public delegate SalesEmployee SalesEmployeeDelegate();

Example

namespace MyEmployeesDelegate

{

//Define a delegate pointing to methods returning Employee types.

public delegate Employee EmployeeDelegate();

//a new delegate pointing to methods returning SalesEmployee types.

public delegate SalesEmployee SalesEmployeeDelegate();

class Program

{

public static Employee GetEmployee()

{

return new Employee();

}

public static SalesEmployee GetSalesEmployee()

{

return new SalesEmployee();

}

static void Main(string[] args)

{

EmployeeDelegate empDel = new EmployeeDelegate(GetEmployee);

Employee emp = empDel();

SalesEmployeeDelegate salesEmpDel = new SalesEmployeeDelegate(GetSalesEmployee);

SalesEmployee emp2 = salesEmpDel();

}

}

public class Employee

{

protected string firstName;

protected string lastName;

protected int Age;

public Employee()

{ }

public Employee(string fName, string lName, int age)

{

this.firstName = fName;

this.lastName = lName;

this.Age = age;

}



}

public class SalesEmployee : Employee

{

protected int salesNumber;

public SalesEmployee()

{ }

public SalesEmployee(string fName, string lName, int age, int sNumber): base(fName, lName, age)

{

this.salesNumber = sNumber;

}

}

}


It would be ideal to build a single delegate type that can point to methods returning either Employee or SelesEmployee types.
Covariance allows you to build a single delegate that can point to methods returning class types related by classical inheritance.

Delegate Covariance Example

namespace DelegateCovariance

{

//Define a single delegate that may return an Employee

// or SalesEmployee

public delegate Employee EmployeeDelegate();

class Program

{

public static Employee GetEmployee()

{

return new Employee();

}

public static SalesEmployee GetSalesEmployee()

{

return new SalesEmployee();

}

static void Main(string[] args)

{

EmployeeDelegate emp = new EmployeeDelegate(GetEmployee);

Employee emp1 = emp();

EmployeeDelegate empB = new EmployeeDelegate(GetSalesEmployee);

//to obtain a derived type you must perform an explicit cast.

SalesEmployee emp2 = (SalesEmployee)empB();

}

}

public class Employee

{

protected string firstName;

protected string lastName;

protected int Age;

public Employee()

{ }

public Employee(string fName, string lName, int age)

{

this.firstName = fName;

this.lastName = lName;

this.Age = age;

}

}

public class SalesEmployee : Employee

{

protected int salesNumber;

public SalesEmployee()

{ }

public SalesEmployee(string fName, string lName, int age, int sNumber): base(fName, lName, age)

{

this.salesNumber = sNumber;

}

}

}


I hope you are now have a good idea with the creation and usage of delegates types.

Generics in C# (CSharp)




Generics are the most useful C# 2.0 language extensions, beside Anonymous methods, Iterators, Partial types And Nullable types.

What are generics?

Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate.

Why generics?

To well know the useful of generics lets examine the following code:

public class Stack
{
object[] items;
int count;
public void Push(object item) {...}
public object Pop() {...}
}


We use the object type to store any type of data. The above simple Stack class stores its data in an object array, and its two methods, Push and Pop, use object to accept and return data. While the use of type object makes the Stack class very flexible, it is not without drawbacks. For example, it is possible to push a value of any type, such a Customer instance, onto a stack.

However, when a value is retrieved, the result of the Pop method must explicitly be cast back to the appropriate type, which is tedious to write and carries a performance penalty for run-time type checking:

Stack stack = new Stack();
stack.Push(new Customer());
Customer c = (Customer)stack.Pop();


If a value of a value type, such as an int, is passed to the Push method, it is automatically boxed. When the int is later retrieved, it must be unboxed with an explicit type cast:

Stack stack = new Stack();
stack.Push(3);
int i = (int)stack.Pop();


Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.

A further issue with the Stack class is that it is not possible to enforce the kind of data placed on a stack. Indeed, a Customer instance can be pushed on a stack and then accidentally cast it to the wrong type after it is retrieved:

Stack stack = new Stack();
stack.Push(new Customer());
string s = (string)stack.Pop();


While the code above is an improper use of the Stack class, the code is technically speaking correct and a compile-time error is not reported. The problem does not become apparent until the code is executed, at which point an InvalidCastException is thrown.

With generics those problems are all solved. HOW...?

public class Stack
{
T[] items;
int count;
public void Push(T item) {...}
public T Pop() {...}
}


When the generic class Stack is used, the actual type to substitute for T is specified. In the following example, int is given as the type argument for T:

Stack stack = new Stack();
stack.Push(3);
int x = stack.Pop();


The Stack type is called a constructed type. In the Stack type, every occurrence of T is replaced with the type argument int. When an instance of Stack is created, the native storage of the items array is an int[] rather than object[], providing substantial storage efficiency compared to the non-generic Stack. Likewise, the Push and Pop methods of a Stack operate on int values, making it a compile-time error to push values of other types onto the stack, and eliminating the need to explicitly cast values back to their original type when they're retrieved.

Generics provide strong typing, meaning for example that it is an error to push an int onto a stack of Customer objects. Just as a Stack is restricted to operate only on int values, so is Stack restricted to Customer objects, and the compiler will report errors on the last two lines of the following example:

Stack stack = new Stack();
stack.Push(new Customer());
Customer c = stack.Pop();
stack.Push(3); // Type mismatch error
int x = stack.Pop(); // Type mismatch error


It was a breif introduction to generics that will be included in the next version of C# (V 2.0) . which is available now on its beta version with Visual C# 2005 Express Edition Beta 1.

Wednesday, November 19, 2008

Currency Converter Custom Control using asp.net

Currency Converter Custom Control using asp.net

This article describes the details for constructing a custom ASP.NET 2.0 composite control used to convert one form of currency into another. The control consumes a public web service in order to calculate the exchange rate and uses the exchange rate returned from the web service to calculate the value of the exchanged currency.


DOWNLOAD THE SOURCE CODE

How to add alert Javascript coding for Gridview using asp.net

How to add alert Javascript coding for Gridview using asp.net

Sometimes we need to confirm from the client side, whether to proceed for deletion operation or not? We can use this code snippet to add that alert box to the user.

Declarations:
none


CODE:
Protected Sub gvcat_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvcat.RowDataBound

' This block of code is used to confirm the deletion of current record.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim l As Object
' e.Row.Controls(4) is Delete button.
l = e.Row.Controls(4)
l.Attributes.Add("onclick", "javascript:return confirm('Are you sure to delete?')")
End If
End Sub

Creating and Calling a Web Service in Asp.Net

Creating and Calling a Web Service in Asp.Net

Demostrates how Web Service is created and called in Dot Net framework with a simple nice example.
Check it out!
Make sure to read the important info text file to follow the instructions.

CLCIKHERE TO DOWNLOAD SOURCE CODE

asp.net code to Export data grid to Excel

asp.net code to Export data grid to Excel


CLICKHERE TO DOWNLOAD SOURCE CODE

AJAX AutoCompleteExtender using Page Method| ASP.net code

AJAX AutoCompleteExtender using Page Method

Declarations:
Start a Visual Basic ASP.NET AJAX-enabled Web application.
Add a reference to the AjaxControlToolkit.


CODE:

CLICKHERE TO DOWNLOAD SOURCE CODE

ASP.net code for Student score management system

ASP.net code for Student score management system:

CLICKHERE TO DOWNLOAD SOURCE CODE

To run student management score system we need

1-SQL Server 2000
2-IIS or .Net Frame work
how to run


1- Restor database into sql server 2000
2-Edite Connection

<%
Dim cnn as sqlconnection
cnn = new sqlconnection("server=xp;database=studentscore;uid=sa;pwd=123")
%>

Run it
Enjoy.....



CLICKHERE TO DOWNLOAD SOURCE CODE

Tuesday, November 11, 2008

how to implement multithreaded TCP/UDP client/server(csharp code)

Source code demonstrating how to implement multithreaded TCP/UDP client/server.

CLICKHERE TO DOWNLOAD SOURCE CODE

The Server: The simple multi-threaded TCP/UDP Server v1 provides a TCP and UDP servers running at separate threads. The sockets can receive a text messages send frm the client machine, and return a confirmation together with the received text back to the client. It uses the traditional socket programming methods (socket/bind/listen/accept). In the v2 of this program, I will make use if the .Net library's TcpListener? that will make things much easier.

The Client: The simple TCP/UDP Client v2 allows users to send a simple text message to the server and get a confirm message from the server. Users can either use TCP or UDP to send this message. The program uses the traditional socket programming technique (socket/bind/connect/send). In v2 of this program, I will make use of .Net library's TcpClient? and UdpClient?, that will make things much easier.

To demo the program, the user has to run the server and the client on separate machines. It he/she wants to run both server and client on the same machine, the server's host name has to be the machine's host name. That is, it can't be "localhost". If "localhost" is used, there will be a socket exception. I still can't figure out why yet.

All the other required information is provided at the beginning of each file.

This post intends to be a beginner level of server/client socket programming and multi-threading demo.


CLICKHERE TO DOWNLOAD SOURCE CODE

c#(csharp)code for drawing circles and rectangles using the multithreaded concepts.

This code is for drawing circles and rectangles using the multithreaded concepts.


CLICKHERE TO DOWNLOAD SOURCE CODE

Multithreading In C#(Csharp) | threading in csharp

Introduction:

In this article let us see about multithreading. Multithreaded applications provide the illusion that numerous activities are happening at more or less the same time. In C# the System.Threading namespace provides a number of types that enable multithreaded programming.

Threading in C#


System.Threading Namespace

The System.Threading Namespace provides a number of types that enable multi-threading programming. In addition to providing types that represent a particular thread, this namespace also describe types that can handle a collection of threads (Thread Pool), a simple (Non -GUI based) Timer class and several types to provide synchronized access to shared data.

The most primitive of all types in the System.Threading namespace is Thread.

Thread:

Represents a thread that executes with in the CLR. Using this type, one can able to spawn additional threads in the owning AppDomain?.This type defines a number of methods (both static and shared) that allow us to create new threads from a current thread, as well as suspend, stop, and destroy a given thread.

The following example will demonstrate Spawning of Secondary threads using C#.


internal class EmployeeClass?
{
public void Performjob()
{

// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i=0;i<10;i++)
{
Console.write(i +",");
}
console.writeline();
}
}

The above code simply prints out a series of numbers by way of the performjob() member function.
Now assume that a class (Main class) creates a new instance of EmployeeClass?. In order for the Main class to continue processing its workflow, it creates and starts a new thread that is used by the job. In the code below, notice that Thread type requests a new Threadstart delegate type:


Public class Mainclass
{
public static int Main (string[] args)
{
Console.Writeline("ID of primary thread is {0}",
Thread.CurrentTHread.GetHashCode() );

// Make Employee class.

EmployeeClass j = new EmployeeClass();

// Now make and start the background thread.

Thread backgroundThread =
new Thread(new ThreadStart(j.Performjob));
backgroundThread.Start();
return 0;
}
}

If we run the application we would find the following result.
ID of primary thread is: 2
ID of Employee thread is: 11
Employee says: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Press any key to continue

From the above example one can easily know how to spawning the secondary Threads.
Let us see another example regarding two active threads.


internal class EmployeeClass
{
public void Performjob()
{
// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i = 0; i < 20000 ; i++)
{
Console.write(i +",");
}
console.writeline();
}
}

Public class Mainclass
{
public static int Main (string[] args)
{
// Make Employee class
............
//Now make the thread.
............
//Now while background thread is working
//do some additional work.
MessageBox?.show("BUSY");
return(0);
}
}

If we run this application we would see that the message box is displayed and it can be moved around the desktop, while the background Employee thread is busy pumping numbers to the console.

Thread Synchronization:

A multithreaded application usually has resources that can be accessed from multiple threads; for example, a global variable that is incremented or decremented by multiple threads. It is sometimes desirable to prevent multiple threads from concurrently altering the state of a resource. The .NET Framework includes several classes and data types that we can use to synchronize actions performed by two threads.

The simplest case is if we have a shared variable that we need to update from different threads. To do this, we can use the System.Threading.Interlocked class. For example, to increment or decrement the shared variable called num, we'd write Interlocked.Increment(num) or Interlocked.Decrement(num). we can also use Interlocked to set the variables to a specific value or to check the equality of two variables.

If there's a section of code in an object's method that should not be accessed concurrently by multiple threads, we can use the Monitor class to acquire a lock on that object by calling Monitor.Enter(object). Any other thread wanting to execute the same code would need to acquire the same lock and will be paused until the first thread releases the lock by calling Monitor. Exit(object).

For more control over thread synchronization or for cross-process synchronization, use the Mutex class, which is a named synchronization object that can be obtained from any thread in any process. Once we create or obtain the mutex, we use its GetHandle? method to (as we'd expect) get a handle that we can use with the WaitHandle?.WaitAny or WaitHandle?.WaitAll methods. These two methods are blocking and will return only if the specified handle is signaled (that is, the mutex is not being used by another thread) or if the specified timeout expires. After we obtain the mutex, we perform the necessary synchronized processing and then call Mutex.ReleaseMutex to release it.

Sometimes we need a mechanism for one thread to notify other threads of some interesting event that occurred. In those cases we can use the .NET synchronization event classes, ManualResetEvent? and AutoResetEvent?. In the world of thread synchronization, an event is an object that has two states: signaled and nonsignaled. An event has a handle and can be used with WaitHandle? just like a mutex. A thread that waits for an event will be blocked until another thread signals the event by calling ManualResetEvent?.Set or AutoResetEvent?.Set. If we are using a ManualResetEvent?, we must call its Reset method to put it back to the nonsignaled state. An AutoResetEvent? will automatically go back to nonsignaled as soon as a waiting thread is notified that the event became signaled.

Conclusion:

That's all it takes to create a multi-threaded application in C#.The System.Threading namespace in .NET SDK makes multi-threading easy.The System.Threading Namespace provides a number of types that enable multi-threading programming easily in C#. The Thread class in the System.Threading namespace exposes the properties and methods to allow the free threading.

C #(Csharp) code to how to play a wave file (.wav) using PlaySound() from the winmm.dll

See how to play a wave file (.wav) using PlaySound() from the winmm.dll


SOURCE CODE:
// play a wave file using PlaySound() from the winmm.dll
// a Windows Application

using System;
using System.Runtime.InteropServices; // DllImport()
using System.Drawing;
using System.Windows.Forms;

namespace PlayWave1?
{

public class WAVSounds
{
DllImport("WinMM.dll")
public static extern bool PlaySound(byte[]wfname, int fuSound);

// possible values for SoundFlags argument in PlaySound from mmsystem.h
public int SND_SYNC = 0x0000; // play synchronously (default)
public int SND_ASYNC = 0x0001; // play asynchronously
public int SND_NODEFAULT = 0x0002; // silence (!default) if sound not found
public int SND_MEMORY = 0x0004; // pszSound points to a memory file
public int SND_LOOP = 0x0008; // loop the sound until next PlaySound
public int SND_NOSTOP = 0x0010; // don't stop any currently playing sound
public int SND_NOWAIT = 0x00002000; // don't wait if the driver is busy
public int SND_ALIAS = 0x00010000; // name is a Registry alias
public int SND_ALIAS_ID = 0x00110000; // alias is a predefined ID
public int SND_FILENAME = 0x00020000; // name is file name
public int SND_RESOURCE = 0x00040004; // name is resource name or atom
public int SND_PURGE = 0x0040; // purge non-static events for task
public int SND_APPLICATION = 0x0080; // look for application-specific association

public void Play(string wfname,int SoundFlags)
{
byte[] bname = new Byte256; //Max path length
bname = System.Text.Encoding.ASCII.GetBytes(wfname);
PlaySound(bname,SoundFlags);
}

public void StopPlay()
{
PlaySound(null,SND_PURGE);
}
} //End WAVSounds class


// Description of MainForm?.
public class MainForm? : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnPlay;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Button btnLoadFile;
public MainForm()
{
InitializeComponent();

openFileDialog1.Title = "Select a Wave Sound File";
openFileDialog1.Filter = "Wav Files(*.wav)|*.wav";
}

STAThread
public static void Main(string[] args)
{
Application.Run(new MainForm());
}

#region Windows Forms Designer generated code
private void InitializeComponent() {
this.btnLoadFile = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.btnStop = new System.Windows.Forms.Button();
this.btnPlay = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnLoadFile
//
this.btnLoadFile.Location = new System.Drawing.Point(24, 16);
this.btnLoadFile.Name = "btnLoadFile";
this.btnLoadFile.Size = new System.Drawing.Size(120, 23);
this.btnLoadFile.TabIndex = 0;
this.btnLoadFile.Text = "Load File";
this.btnLoadFile.Click += new System.EventHandler(this.BtnLoadFileClick);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(24, 112);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(128, 23);
this.btnStop.TabIndex = 2;
this.btnStop.Text = "Stop";
this.btnStop.Click += new System.EventHandler(this.BtnStopClick);
//
// btnPlay
//
this.btnPlay.Location = new System.Drawing.Point(24, 64);
this.btnPlay.Name = "btnPlay";
this.btnPlay.Size = new System.Drawing.Size(120, 23);
this.btnPlay.TabIndex = 1;
this.btnPlay.Text = "Play";
this.btnPlay.Click += new System.EventHandler(this.BtnPlayClick);
//
// MainForm?
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255)));
this.ClientSize = new System.Drawing.Size(304, 266);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnPlay);
this.Controls.Add(this.btnLoadFile);
this.Name = "MainForm";
this.Text = "MainForm";
this.ResumeLayout(false);
}
#endregion

void BtnLoadFileClick(object sender, System.EventArgs e)
{
openFileDialog1.ShowDialog();
}

void BtnPlayClick(object sender, System.EventArgs e)
{
WAVSounds ws = new WAVSounds();
ws.Play(openFileDialog1.FileName,ws.SND_ASYNC);
}

void BtnStopClick(object sender, System.EventArgs e)
{
WAVSounds ws = new WAVSounds();
ws.StopPlay();
}
}
}

how to use the waveout API from C#|low-level audio player in C#



CLICKHERE TO DOWNLOAD SOURCE CODE

Introduction:
It is no news that the .NET framework does not include any classes for dealing with sound. Some people have worked around this limitation by wrapping high-level system components, such as Windows Media Player or DirectShow?, into .NET-friendly libraries. However, most of these libraries are designed in such a way that they cannot be used to manipulate audio samples on the fly because they do not give you access to the actual sound data.

When developing applications that deal with such low-level issues, the most commonly used technologies are DirectSound? and the waveout API. This article describes a sample application that uses the waveout API in C# through Interop to play a WAV file in a continuous loop.

Using the code:
Most of the work in the sample application is carried out by two classes: WaveStream? and WaveOutPlayer?.

The WaveStream? class extends System.IO.Stream and implements the necessary code to read audio samples from a WAV file. The constructor reads the file header and extracts all the relevant information including the actual length of the stream and the format of the audio samples, which is exposed through the Format property.

One important thing to note is that seeking operations in the WaveStream? class are relative to the sound data stream. This way you don't have to care about the length of the header or about those extra bytes at the end of the stream that don't belong to the audio data chunk. Seeking to 0 will cause the next read operation to start at the beginning of the audio data.

The WaveOutPlayer? class is where the most interesting things happen. For the sake of simplicity, the interface of this class has been reduced to the strict minimum. There are no Start, Stop or Pause methods. Creating an instance of WaveOutPlayer? will cause the system to start streaming immediately.

Let's have a look at the code that creates the WaveOutPlayer? instance. As you can see, the constructor takes five parameters:


private void Play()
{
Stop();
if (m_AudioStream != null)
{
m_AudioStream.Position = 0;
m_Player = new WaveLib?.WaveOutPlayer(-1, m_Format, 16384, 3,
new WaveLib?.BufferFillEventHandler(Filler));
}
}

The first parameter is the ID of the wave device that you want to use. The value -1 represents the default system device, but if your system has more than one sound card, then you can pass any number from 0 to the number of installed sound cards minus one to select a particular device.

The second parameter is the format of the audio samples. In this example, the format is taken directly from the wave stream.

The third and forth parameters are the size of the internal wave buffers and the number of buffers to allocate. You should set these to reasonable values. Smaller buffers will give you less latency, but the audio may stutter if your computer is not fast enough.

The fifth and last parameter is a delegate that will be called periodically as internal audio buffers finish playing, so that you can feed them with new sound data. In the sample application we just read audio data from the wave stream, like this:


private void Filler(IntPtr data, int size)
{
byte[] b = new bytesize;
if (m_AudioStream != null)
{
int pos = 0;
while (pos < size)
{
int toget = size - pos;
int got = m_AudioStream.Read(b, pos, toget);
if (got < toget)
m_AudioStream.Position = 0; // loop if the file ends
pos += got;
}
}
else
{
for (int i = 0; i < b.Length; i++)
bi = 0;
}
System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
}

Please note that this delegate may be called from any internal thread created by the WaveOutPlayer? object, so if you want to call into your Windows Forms objects you should use the Invoke mechanism.

To stop playing, just call Dispose on the player object, like this:


private void Stop()
{
if (m_Player != null)
try
{
m_Player.Dispose();
}
finally
{
m_Player = null;
}
}

CLICKHERE TO DOWNLOAD SOURCE CODE

How to play multimedia files (wav, mp3, wma.) using MCI

Play multimedia files using MCI and C#

Multimedia can enhance the graphical user interface and the presentation of your application. It is very important that you application is visual appealing to your user, but while not making your application difficult to work with. You can use a sound file to notify a user of an event, or a video file demonstrating what the user must do next. I have wrapped most of the common MCI multimedia command in a class file. This will make it easier for you to use MCI in your applications.


Media Control Interface (MCI)

The Media Control Interface (MCI) provides standard commands for playing multimedia devices and recording multimedia resource files. These commands are a generic interface to nearly every kind of multimedia device. MCI provides applications with device-independent capabilities for controlling audio and visual peripherals. Your application can use MCI to control any supported multimedia device, including waveform-audio devices, MIDI sequencers, CD audio devices, and digital-video (video playback) devices.


mciSendString

The mciSendString function sends a command string to an MCI device. The device that the command is sent to is specified in the command string.


Enter the code

First we import the “winmm.dll” so that we can use the mciSendString function that we need.


DllImport("winmm.dll")

private static extern long mciSendString(string strCommand,

StringBuilder? strReturn, int iReturnLength, IntPtr? hwndCallback);


strCommand


Pointer to a null-terminated string that specifies an MCI command string.

For a list, see Multimedia Command Strings.


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_multimedia_command_strings.asp


strReturn


Pointer to a buffer that receives return information. If no return information is needed, this parameter can be null

.

iReturnLength


Size, in characters, of the return buffer specified by the strReturn parameter.


hwndCallback


Handle to a callback window if the "notify" flag was specified in the command string.


The open command


The open command initializes a device. All MCI devices recognize this command.

To send this command, call the mciSendString function with the strCommand parameter set as follows.



public void Open(string sFileName)
{

//mpegvideo is the device type that
//we are going to use
//the format of the song location
//must be with double quotes around it

sCommand = "open \"" + sFileName + "\" type

mpegvideo alias MediaFile";

mciSendString(sCommand, null, 0, IntPtr?.Zero);

}



We are using the mpegvideo device because we can play almost all of the newest media files with it, e.g. divx, xvid, mp3, avi, wav, mpeg, mpg and wmv.


The play command


The play command starts playing a device. CD audio, digital-video, MIDI sequencer, videodisc, VCR, and waveform-audio devices recognize this command. To send this command, call the mciSendString function with the strCommand parameter set as follows.



public void Play()
{
//tell the device to play

sCommand = "play MediaFile";

mciSendString(sCommand, null, 0, IntPtr?.Zero);

}


Conclusion:

I have only covered the basics in this tutorial; there are a lot more MCI function sitting in the wrapper that I wrote. Download the attached source code and demo application to get an idea of how to use the wrapper. You are all welcome to take the wrapper an improve/change it to suit your needs.


Happy coding !!!!


CLICKHERE TO DOWNLOAD SOURCE CODE

How to play an mp3 file in C#, using MCI (from winmm.dll)

This article will show you how to play an mp3 file in C#, using MCI (from winmm.dll). There is sample code and explanations!


CLICKHERE TO DOWNLOAD SOURCE CODE

C#(csharp) Code to Reads/writes mp3 Id3v1 tags.

Reads/writes mp3 Id3v1 tags

SOURCE CODE:
using System;
using System.IO;
using System.Text;

namespace mp3info
{

public class ID3v1
{
public string filename;

public string Title;
public string Artist;
public string Album;
public string Year;
public string Comment;
public int GenreID;
public int Track;

public bool hasTag;

private void Initialize_Components()
{
hasTag = false;
filename = "";
Title = "";
Artist = "";
Album = "";
Year = "";
Comment = "";

GenreID = 0;
Track = 0;
}


public ID3v1()
{
Initialize_Components();
}

public ID3v1( string filename )
{
Initialize_Components();
this.filename = filename;
}


public void Read ()
{
// Read the 128 byte ID3 tag into a byte array
FileStream? oFileStream;
oFileStream = new FileStream( this.filename, FileMode?.Open);
byte[] bBuffer = new byte128;
oFileStream.Seek(-128, SeekOrigin?.End);
oFileStream.Read(bBuffer,0, 128);
oFileStream.Close();

// Convert the Byte Array to a String
Encoding instEncoding = new ASCIIEncoding(); // NB: Encoding is an Abstract class
string id3Tag = instEncoding.GetString(bBuffer);

// If there is an attched ID3 v1.x TAG then read it
if (id3Tag .Substring(0,3) == "TAG")
{
this.Title = id3Tag.Substring( 3, 30).Trim();
this.Artist = id3Tag.Substring( 33, 30).Trim();
this.Album = id3Tag.Substring( 63, 30).Trim();
this.Year = id3Tag.Substring( 93, 4).Trim();
this.Comment = id3Tag.Substring( 97,28).Trim();

// Get the track number if TAG conforms to ID3 v1.1
if (id3Tag125==0)
this.Track = bBuffer126;
else
this.Track = 0;
this.GenreID = bBuffer127;

this.hasTag = true;
// ********* IF USED IN ANGER: ENSURE to test for non-numeric year
}
else
{
this.hasTag = false;
}
}

public void updateMP3Tag ()
{
// Trim any whitespace
this.Title = this.Title.Trim();
this.Artist = this.Artist.Trim();
this.Album = this.Album.Trim();
this.Year = this.Year.Trim();
this.Comment = this.Comment.Trim();

// Ensure all properties are correct size
if (this.Title.Length > 30) this.Title = this.Title.Substring(0,30);
if (this.Artist.Length > 30) this.Artist = this.Artist.Substring(0,30);
if (this.Album.Length > 30) this.Album = this.Album.Substring(0,30);
if (this.Year.Length > 4) this.Year = this.Year.Substring(0,4);
if (this.Comment.Length > 28) this.Comment = this.Comment.Substring(0,28);

// Build a new ID3 Tag (128 Bytes)
byte[] tagByteArray = new byte128;
for ( int i = 0; i < tagByteArray.Length; i++ ) tagByteArrayi = 0; // Initialise array to nulls

// Convert the Byte Array to a String
Encoding instEncoding = new ASCIIEncoding(); // NB: Encoding is an Abstract class // ************ To DO: Make a shared instance of ASCIIEncoding so we don't keep creating/destroying it
// Copy "TAG" to Array
byte[] workingByteArray = instEncoding.GetBytes("TAG");
Array.Copy(workingByteArray, 0, tagByteArray, 0, workingByteArray.Length);
// Copy Title to Array
workingByteArray = instEncoding.GetBytes(this.Title);
Array.Copy(workingByteArray, 0, tagByteArray, 3, workingByteArray.Length);
// Copy Artist to Array
workingByteArray = instEncoding.GetBytes(this.Artist);
Array.Copy(workingByteArray, 0, tagByteArray, 33, workingByteArray.Length);
// Copy Album to Array
workingByteArray = instEncoding.GetBytes(this.Album);
Array.Copy(workingByteArray, 0, tagByteArray, 63, workingByteArray.Length);
// Copy Year to Array
workingByteArray = instEncoding.GetBytes(this.Year);
Array.Copy(workingByteArray, 0, tagByteArray, 93, workingByteArray.Length);
// Copy Comment to Array
workingByteArray = instEncoding.GetBytes(this.Comment);
Array.Copy(workingByteArray, 0, tagByteArray, 97, workingByteArray.Length);
// Copy Track and Genre to Array
tagByteArray126 = System.Convert.ToByte(this.Track);
tagByteArray127 = System.Convert.ToByte(this.GenreID);

// SAVE TO DISK: Replace the final 128 Bytes with our new ID3 tag
FileStream? oFileStream = new FileStream(this.filename , FileMode?.Open);
if (this.hasTag)
oFileStream.Seek(-128, SeekOrigin?.End);
else
oFileStream.Seek(0, SeekOrigin?.End);
oFileStream.Write(tagByteArray,0, 128);
oFileStream.Close();
this.hasTag = true;
}

}
}

c# code to View/Change Windows Master Volume

See how to display and modify Windows's Master Volume, without using DirectShow?, but rather than that, directly manipulating the windows mixer.


SOURCE CODE:
using System;
using System.Runtime.InteropServices;

public class AudioMixerHelper?
{
public const int MMSYSERR_NOERROR = 0;
public const int MAXPNAMELEN = 32;
public const int MIXER_LONG_NAME_CHARS = 64;
public const int MIXER_SHORT_NAME_CHARS = 16;
public const int MIXER_GETLINEINFOF_COMPONENTTYPE = 0x3;
public const int MIXER_GETCONTROLDETAILSF_VALUE = 0x0;
public const int MIXER_GETLINECONTROLSF_ONEBYTYPE = 0x2;
public const int MIXER_SETCONTROLDETAILSF_VALUE = 0x0;
public const int MIXERLINE_COMPONENTTYPE_DST_FIRST = 0x0;
public const int MIXERLINE_COMPONENTTYPE_SRC_FIRST = 0x1000;
public const int MIXERLINE_COMPONENTTYPE_DST_SPEAKERS =
(MIXERLINE_COMPONENTTYPE_DST_FIRST + 4);
public const int MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE =
(MIXERLINE_COMPONENTTYPE_SRC_FIRST + 3);
public const int MIXERLINE_COMPONENTTYPE_SRC_LINE =
(MIXERLINE_COMPONENTTYPE_SRC_FIRST + 2);
public const int MIXERCONTROL_CT_CLASS_FADER = 0x50000000;
public const int MIXERCONTROL_CT_UNITS_UNSIGNED = 0x30000;
public const int MIXERCONTROL_CONTROLTYPE_FADER =
(MIXERCONTROL_CT_CLASS_FADER | MIXERCONTROL_CT_UNITS_UNSIGNED);
public const int MIXERCONTROL_CONTROLTYPE_VOLUME =
(MIXERCONTROL_CONTROLTYPE_FADER + 1);

DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerClose (int hmx);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerGetControlDetailsA (int hmxobj,ref
MIXERCONTROLDETAILS pmxcd , int fdwDetails);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerGetDevCapsA(int uMxId, MIXERCAPS
pmxcaps, int cbmxcaps);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerGetID (int hmxobj, int pumxID, int
fdwId);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerGetLineControlsA (int hmxobj,ref
MIXERLINECONTROLS pmxlc, int fdwControls);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerGetLineInfoA (int hmxobj,ref
MIXERLINE pmxl , int fdwInfo);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerGetNumDevs();
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerMessage(int hmx , int uMsg , int
dwParam1 , int dwParam2);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerOpen (out int phmx , int uMxId ,
int dwCallback , int dwInstance , int fdwOpen);
DllImport("winmm.dll", CharSet=CharSet.Ansi)
private static extern int mixerSetControlDetails(int hmxobj ,ref
MIXERCONTROLDETAILS pmxcd , int fdwDetails);

public struct MIXERCAPS
{
public int wMid;
public int wPid;
public int vDriverVersion;
MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAXPNAMELEN)
public string szPname;
public int fdwSupport;
public int cDestinations;
}

public struct MIXERCONTROL
{
public int cbStruct;
public int dwControlID;
public int dwControlType;
public int fdwControl;
public int cMultipleItems;
MarshalAs( UnmanagedType.ByValTStr,
SizeConst=MIXER_SHORT_NAME_CHARS)
public string szShortName ;
MarshalAs( UnmanagedType.ByValTStr,
SizeConst=MIXER_LONG_NAME_CHARS)
public string szName;
public int lMinimum;
public int lMaximum;
MarshalAs(UnmanagedType.U4, SizeConst=10)
public int reserved;
}

public struct MIXERCONTROLDETAILS
{
public int cbStruct;
public int dwControlID;
public int cChannels;
public int item;
public int cbDetails;
public IntPtr? paDetails;
}

public struct MIXERCONTROLDETAILS_UNSIGNED
{
public int dwValue;
}

public struct MIXERLINE
{
public int cbStruct;
public int dwDestination;
public int dwSource;
public int dwLineID;
public int fdwLine;
public int dwUser;
public int dwComponentType;
public int cChannels;
public int cConnections;
public int cControls;
MarshalAs(UnmanagedType.ByValTStr,
SizeConst=MIXER_SHORT_NAME_CHARS)
public string szShortName;
MarshalAs(UnmanagedType.ByValTStr,
SizeConst=MIXER_LONG_NAME_CHARS )
public string szName;
public int dwType;
public int dwDeviceID;
public int wMid;
public int wPid;
public int vDriverVersion ;
MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAXPNAMELEN)
public string szPname ;
}

public struct MIXERLINECONTROLS
{
public int cbStruct;
public int dwLineID;

public int dwControl;
public int cControls;
public int cbmxctrl;
public IntPtr? pamxctrl;
}

private static bool GetVolumeControl(int hmixer, int componentType,
int ctrlType, out MIXERCONTROL mxc, out int vCurrentVol)
{
// This function attempts to obtain a mixer control.
// Returns True if successful.
MIXERLINECONTROLS mxlc = new MIXERLINECONTROLS();
MIXERLINE mxl = new MIXERLINE();
MIXERCONTROLDETAILS pmxcd = new MIXERCONTROLDETAILS();
MIXERCONTROLDETAILS_UNSIGNED du = new
MIXERCONTROLDETAILS_UNSIGNED();
mxc = new MIXERCONTROL();
int rc;
bool retValue;
vCurrentVol = -1;

mxl.cbStruct = Marshal.SizeOf(mxl);
mxl.dwComponentType = componentType;

rc = mixerGetLineInfoA(hmixer,ref mxl,
MIXER_GETLINEINFOF_COMPONENTTYPE );

if(MMSYSERR_NOERROR == rc)
{
int sizeofMIXERCONTROL = 152;
int ctrl = Marshal.SizeOf(typeof(MIXERCONTROL));
mxlc.pamxctrl = Marshal.AllocCoTaskMem(sizeofMIXERCONTROL);
mxlc.cbStruct = Marshal.SizeOf(mxlc);
mxlc.dwLineID = mxl.dwLineID;
mxlc.dwControl = ctrlType;
mxlc.cControls = 1;
mxlc.cbmxctrl = sizeofMIXERCONTROL;

// Allocate a buffer for the control
mxc.cbStruct = sizeofMIXERCONTROL;

// Get the control
rc = mixerGetLineControlsA(hmixer,ref mxlc,
MIXER_GETLINECONTROLSF_ONEBYTYPE);

if(MMSYSERR_NOERROR == rc)
{
retValue = true;

// Copy the control into the destination structure
mxc = (MIXERCONTROL)Marshal.PtrToStructure(
mxlc.pamxctrl,typeof(MIXERCONTROL));
}
else
{
retValue = false;
}
int sizeofMIXERCONTROLDETAILS =
Marshal.SizeOf(typeof(MIXERCONTROLDETAILS));
int sizeofMIXERCONTROLDETAILS_UNSIGNED =
Marshal.SizeOf(typeof(MIXERCONTROLDETAILS_UNSIGNED));
pmxcd.cbStruct = sizeofMIXERCONTROLDETAILS;
pmxcd.dwControlID = mxc.dwControlID;
pmxcd.paDetails =

Marshal.AllocCoTaskMem(sizeofMIXERCONTROLDETAILS_UNSIGNED) ;
pmxcd.cChannels = 1;
pmxcd.item = 0;
pmxcd.cbDetails = sizeofMIXERCONTROLDETAILS_UNSIGNED;

rc = mixerGetControlDetailsA(hmixer,ref pmxcd,
MIXER_GETCONTROLDETAILSF_VALUE);

du = (MIXERCONTROLDETAILS_UNSIGNED)Marshal.PtrToStructure(
pmxcd.paDetails, typeof(MIXERCONTROLDETAILS_UNSIGNED));

vCurrentVol = du.dwValue;

return retValue;
}

retValue = false;
return retValue;
}

private static bool SetVolumeControl(int hmixer, MIXERCONTROL mxc,
int volume)
{
// This function sets the value for a volume control.
// Returns True if successful

bool retValue;
int rc;
MIXERCONTROLDETAILS mxcd = new MIXERCONTROLDETAILS();
MIXERCONTROLDETAILS_UNSIGNED vol = new
MIXERCONTROLDETAILS_UNSIGNED();

mxcd.item = 0;
mxcd.dwControlID = mxc.dwControlID;
mxcd.cbStruct = Marshal.SizeOf(mxcd);
mxcd.cbDetails = Marshal.SizeOf(vol);

// Allocate a buffer for the control value buffer
mxcd.cChannels = 1;
vol.dwValue = volume;

// Copy the data into the control value buffer
mxcd.paDetails = Marshal.AllocCoTaskMem(Marshal.SizeOf(
typeof(MIXERCONTROLDETAILS_UNSIGNED)));
Marshal.StructureToPtr(vol, mxcd.paDetails,false);

// Set the control value
rc = mixerSetControlDetails(hmixer,ref mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);

if(MMSYSERR_NOERROR == rc)
{
retValue = true;
}
else
{
retValue = false;
} return retValue;
}

public static int GetVolume()
{
int mixer;
MIXERCONTROL volCtrl = new MIXERCONTROL();
int currentVol;
mixerOpen(out mixer,0 ,0 ,0, 0);
int type = MIXERCONTROL_CONTROLTYPE_VOLUME;
GetVolumeControl(mixer,
MIXERLINE_COMPONENTTYPE_DST_SPEAKERS,type,out volCtrl, out
currentVol);
mixerClose(mixer);

return currentVol;
}

public static void SetVolume(int vVolume)
{
int mixer;
MIXERCONTROL volCtrl = new MIXERCONTROL();
int currentVol;
mixerOpen(out mixer,0 ,0 ,0, 0);
int type = MIXERCONTROL_CONTROLTYPE_VOLUME;
GetVolumeControl(mixer,
MIXERLINE_COMPONENTTYPE_DST_SPEAKERS,type,out volCtrl, out
currentVol);
if(vVolume > volCtrl.lMaximum) vVolume = volCtrl.lMaximum;
if(vVolume < volCtrl.lMinimum) vVolume = volCtrl.lMinimum;
SetVolumeControl(mixer, volCtrl, vVolume);
GetVolumeControl(mixer,
MIXERLINE_COMPONENTTYPE_DST_SPEAKERS,type,out volCtrl, out
currentVol);
if(vVolume != currentVol)
{
throw new Exception("Cannot Set Volume");
}
mixerClose(mixer);
}
}

Usage:


private void button1_Click(object sender, System.EventArgs e)
{
//Display the current master volume
MessageBox?.Show(AudioMixerHelper.GetVolume().ToString());
//set the master volume
AudioMixerHelper?.SetVolume(1000);
//Display the new volume
MessageBox?.Show(AudioMixerHelper.GetVolume().ToString());
}

C# program that plays mp3, using lame.exe

Here is an example C# program that plays mp3, using lame.exe converts wav to mp3, records and plays wav files using MCI.

Download Source Code

You will need lame.exe.
Get it here: http://www.mp3dev.org/mp3/
put it in the c:\ directory to use my defaults

I did assemble this program,but I got the info from various sources. I decided to assemble this example after spending several hours searching for this type of information for C#.
Remember that 'int, uint' in C# is the same length (32 bits, 4 bytes) as a 'long' in visual basic, and DWORD or UINT in C++
Credit given to C# HELP where I found the mp3 example.
Credit given to all the other places I found the winmm.lib info.
Visual C++ example http://www.cs.binghamton.edu/~reckert/360/11.html
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q152180


The end of the file has the lame.exe help file and info on converting types between languages. Put the lame.exe in same directory as your test wave file to convert wav to mp3
First confirm your mic is working
Code your project directory
Record a wave file

To use this as is just put the lame.exe program in the c:\ directory and record a wave don't forget to hit enter to stop the recording
lame.exe is at http://www.webattack.com/get/lame.shtml


CLICKHERE TO DOWNLOAD SOURCE CODE

Access Registry Using C#(csharp)

Access the registry using C#. Find out the system Information. Using this source code.


/* I used it find Processor Information and Bios Information*/

using System;
using Microsoft.Win32;

class reg {
static void Main() {
RegistryKey? hklm =Registry.LocalMachine;
hklm=hklm.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
Object obp=hklm.GetValue("Identifier");
Console.WriteLine("Processor Identifier :{0}",obp);

RegistryKey? hklp =Registry.LocalMachine;
hklp=hklp.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
Object obc=hklp.GetValue("VendorIdentifier");
Console.WriteLine("Vendor Identifier :{0}",obc);

RegistryKey? biosv =Registry.LocalMachine;
biosv=biosv.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\MultiFunctionAdapter\\4");
Object obv=biosv.GetValue("Identifier");
Console.WriteLine("Bios Status :{0}",obv);

RegistryKey? biosd =Registry.LocalMachine;
biosd=biosd.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\");
Object obd=biosd.GetValue("SystemBiosDate");
Console.WriteLine("Bios Date :{0}",obd);

RegistryKey? bios =Registry.LocalMachine;
bios=bios.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\");
Object obs=bios.GetValue("Identifier");
Console.WriteLine("System Identifer :{0}",obs);
}
}

how to manipulate windows registry|Registry Manipulation Basis

1. Basics and key elements

The Windows Registry is the place where most of the settings in Windows and its applications reside. For example, when a user finds the file TEST.TXT in Windows Explorer, it is automatically marked as a text file and Explorer shows the standard "Text file" icon. This behavior is a setting stored in the Registry. Same goes when trying to open that file: the Windows Registry stores the fact that Windows should use Notepad to open the file, and not Media Player, for instance.

The Windows Registry is divided into more subgroups, depending on its purpose:

HKEY_LOCAL_MACHINE - stores machine-specific settings, such as hardware, application settings that apply to all users, etc.

HKEY_CURRENT_USER - stores the current user's settings. It refers to the user that is logged on at the moment. If there are more users logged on, when one of them tries to access this key, it will point to its own settings, and not to the ones of another user

HKEY_CLASSES_ROOT - stores class-specific data. Each application or application element has its own UID (Unique IDentifier) that holds a certain place within this part of the registry. Generally, things like an Internet Explorer toolbar or a plug-in holds its data here, as well as all the known file extensions

HKEY_CURRENT_CONFIG - holds current configuration settings. The key is not very important, as it only holds session-specific data and few miscellaneous settings

HKEY_USERS - stores data about all users. Each user has a UUID (Unique User IDentifier). The HKEY_CURRENT_USER is actually a copy of one of the keys in here. Any modification will be lost if the user is logged on, because HKEY_USERS is automatically overwritten at logoff

The Registry is organized much like the file system in Windows. It has keys (which correspond to folders) and values (which correspond to files). Values can be of a few specific types: String, Binary, DWORD, Multi-string and Expandable String. Due to its limitations, however, C# will interpret the last two types as String types.

2. The perquisites

A C# application cannot access the registry at its own volition. Registry access cannot be granted to any application due to security reasons. It must ask for privileges in order to be able to access the registry.

Keep in mind that the registry is a windows-specific element. It will not be compatible with any other operating system. All classes and methods used to manipulate registry are stored within the "Microsoft.Win32" namespace. Also, keep in mind that registry manipulation is not done by the .NET Framework (or at least not yet implemented). That is why two assembly requests must be made (example):


using System.Security.Permissions;
using Microsoft.Win32;
assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)
assembly:RegistryPermissionAttribute(SecurityAction.RequestMinimum, All="HKEY_LOCAL_MACHINE")

Putting these in front of the namespace used to access registry will do the following:

- Request a permission to execute unmanaged code (the registry manipulation methods are outside the .NET Framework, therefore unmanaged code privilege is needed), signaling that it is a minimal requirement for that namespace or class to be able to execute its code, and inform that the program should fail if this is not fully satisfied
- Request a permission to access the HKEY_LOCAL_MACHINE base key and have access to all available actions (the "All" parameter), again signaling and informing like above

Of course, HKEY_LOCAL_MACHINE can be changed to any of the base classes above and the permission type can be changed from "All" to something else.

Next comes the actual manipulation phase.

3. The manipulation

The .NET Framework provides the "RegistryKey" class that allows registry manipulation.

It is impractical to open a base class manually, so the .NET Framework offers a way to open one automatically. for instance, let's presume we want to open a subclass of the HKEY_LOCAL_MACHINE located in "Software\Microsoft\Windows\CurrentVersion\Run" (the key that holds the programs that start up at boot-time). it can be done simply using the pre-defined method "Microsoft.Win32.Registry.LocalMachine.OpenSubKey()", that returns a RegistryKey? object. For example:


RegistryKey ka=Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", true);

The second parameter of the function is the "write-protect" parameter. If false (or if omitted), the registry key cannot be written.

Here are some examples of using the "RegistryKey" class:


ka.SetValue("GinaDLL", val); // After opening the registry key like specified, it sets the value GinaDLL to the one held in the "val" object; creates a new value if missing

ka.DeleteValue("GinaDLL", false); // After opening the registry key, it deletes the value "GinaDLL"; the second parameter states that if the value is missing, the function should not throw any exceptions

ka.Flush(); //After opening the key and doing some operations, it flushes all modifications to the Registry

ka.Close(); // After a key is opened, this flushes all modifications and then closes it

ka.CreateSubKey("MSGina"); // After a key is opened, this creates a sub-key

ka.DeleteSubKey("MSGina2"); // After a key is opened, this deletes a sub-key and all its contents

ka.DeleteSubKeyTree("ACertainSubKey"); // After opening a key, it deletes a specific sub-key and all its own sub-keys recursively

string[] alfa=ka.GetValueNames(); // Gets all the values currently in that key

That is all about basic registry manipulation. Do not forget to use the "Close" function, because otherwise, any modifications will be lost upon exit or there may be exceptions.

For further reference about C# registry manipulation, please consult MSDN at http://msdn.microsoft.com and for samples, please visit CodeProject? (if available) at http://www.codeproject.com or visit our Registry Manipulation section.

Asteroids game programming in c#(csharp)




It’s a game of Asteroids programmed in C#. It uses GDI+ so a fast enough computer is recommended. There are no external images needed all the sprites are drawn internally. Any comments, improvements would be appreciated.


CLICKHERE TO DOWNLOAD SOURCE CODE

Calculator Program In C#(csharp)

Here is a calculator program written in C#. It will give you the basics of Windows Forms, Arrays, and Controls.

To compile it, just type in:
prompt>csc Calculator.cs



CLICKHERE TO DOWNLOAD SOURCE CODE

Digital Clock in C#(csharp)

This project is a Digital Clock in C#. It uses the Timer Control. Source code and an .exe application are included in the package.


CLICKHER TO DOWNLOAD SOURCE CODE

Image Viewer Application-Winforms & C#(csharp)



The following is an Image viewer application which can
be used to view image files of many formats. This example
is provides a good introduction to Winforms.

For compiling the code, use the following at the command line:

csc /target:winexe /reference:System.dll /reference:System.Winforms.dll /reference:System.Drawing.dll /reference:Microsoft.Win32.Interop.dll PictureViewer?.cs


Source Code:


namespace myPictViewer
{
using System;
using System.WinForms;
using System.Drawing;
public class PictViewForm? : Form
{
protected Bitmap myPicture;
protected bool myPicStyle = true;
protected MenuItem? showWindow;
protected MenuItem? showNative;
protected MenuItem? closePicture;
public PictViewForm()
{
this.Text = "Picture Viewer";
this.ClientSize = new Size(640,480);
MainMenu? myMainMenu = new MainMenu();
MenuItem? myFileItem = myMainMenu.MenuItems.Add("&File");
MenuItem? myHelpItem = myMainMenu.MenuItems.Add("&Help");
//The line below is commented out as it may not work for Beta 1 of .NET
//myFileItem.Popup += new EventHandler? (checkMenus);
myFileItem.MenuItems.Add(new MenuItem("&Open" , new EventHandler(OnOpen) , Shortcut.CtrlO));
myFileItem.MenuItems.Add("-");
myFileItem.MenuItems.Add(showWindow = new MenuItem("Show Image - Fit To Window" , new EventHandler(ShowWindow)));
myFileItem.MenuItems.Add(showNative = new MenuItem("Show Image - Native Size" , new EventHandler(ShowNative)));
myFileItem.MenuItems.Add("-");
myFileItem.MenuItems.Add(closePicture = new MenuItem("&Close Picture" , new EventHandler(OnClose) , Shortcut.CtrlH));
myFileItem.MenuItems.Add(new MenuItem("E&xit" , new EventHandler(OnExit) , Shortcut.CtrlE));

myHelpItem.MenuItems.Add(new MenuItem("&About" , new EventHandler(OnAbout) , Shortcut.CtrlA));
closePicture.Enabled = false;
this.Menu = myMainMenu;
this.StartPosition = FormStartPosition?.CenterScreen;
}

protected override void OnPaint(PaintEventArgs myArgs)
{
if (myPicture != null)
{
Graphics myGraph = myArgs.Graphics;
if (myPicStyle == true)
{
myGraph.DrawImage(myPicture , AutoScrollPosition?.X , AutoScrollPosition?.Y , myPicture.Width , myPicture.Height);
}
else
{
myGraph.DrawImage(myPicture , ClientRectangle);
}
}
}

private void OnAbout(Object mySender , EventArgs? myArgs)
{
MessageBox?.Show("Picture Viewer 1.0 by Jim","About Picture Viewer",MessageBox?.OK|MessageBox.IconInformation);
}

private void checkMenus(Object mySender , EventArgs? myArgs)
{
if (myPicture != null)
{
if (myPicStyle == true)
{
showNative.Checked = true;
showWindow.Checked = false;
}
else
{
showNative.Checked = false;
showWindow.Checked = true;
}
}
else
{
showNative.Checked = false;
showWindow.Checked = false;
myPicStyle = true;
}
}

private void ShowWindow(Object mySender , EventArgs? myArgs)
{
myPicStyle = false;
this.SetStyle (ControlStyles.ResizeRedraw, true);
if (myPicture != null)
{
this.AutoScroll = false;
this.Invalidate();
}
}

private void ShowNative(Object mySender , EventArgs? myArgs)
{
myPicStyle = true;
this.SetStyle (ControlStyles.ResizeRedraw, false);
if (myPicture != null)
{
this.AutoScroll = true;
this.AutoScrollMinSize = myPicture.Size;
this.Invalidate();
}
}

private void OnClose(Object mySender , EventArgs? myArgs)
{
closePicture.Enabled = false;
myPicture = null;
myPicStyle = false;
this.AutoScroll = false;
this.Invalidate();
}

private void OnExit(Object mySender , EventArgs? myArgs)
{
this.Close();
}

private void OnOpen(Object mySender , EventArgs? myArgs)
{
if (myPicture != null)
{

}
OpenFileDialog? myDialog = new OpenFileDialog();
myDialog.Filter = "Image Files (JPEG,GIF,BMP)|*.jpg;*.jpeg;*.gif;*.bmp|JPEG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF Files(*.gif)|*.gif|BMP Files(*.bmp)|*.bmp";

if (myDialog.ShowDialog() == DialogResult?.OK)
{
String myFileName = myDialog.FileName;
if (myFileName.Length != 0)
{
try
{
closePicture.Enabled = true;
myPicture = new Bitmap(myFileName);
this.Text = "Picture Viewer - " + myFileName;
this.AutoScroll = true;
this.AutoScrollMinSize = myPicture.Size;
this.Invalidate();
}
catch
{
MessageBox?.Show(String.Format("{0} is not a valid Image File" , myFileName) , "Picture Viewer" , MessageBox?.OK | MessageBox?.IconError);
}
}
}
}

public static void Main(string[] args)
{
Application.Run(new PictViewForm());
}
}
}

Classic Puzzle Game in C#(csharp)

Here is the C# version of the classic puzzle game. This game demonstrates how to use looping constructs, indexers and properties all in one C# program. This program is not for basic users.

''/*
Author : Prasad
Date : July 12 2001
Purporse : Move Grid Puzzle.This has table of values
with random and one blank cell we have to
arrange it in order.
Input : 0 5 8
7 4 3
2 6 1

Output : 1 2 3
4 5 6
7 8 0

/''


CLICKHERE TO DOWNLOAD SOURCE CODE

Tetris Game in C#(csharp)




Blocking Elements is a Tetris like game made in C#, using GDI+.


CLICKHERE TO DOWNLOAD SOURCE CODE

Dotnet(.Net) Crypto(RC2)



RC2 is a variable key-size block cipher designed by Ronald Rivest for RSA Data Security (now RSA Security). "RC" stands for "Ron's Code" or "Rivest's Cipher.

Read more on CR2



/*
* csharp-home.com or nerdandy@gmail.com for questions and answers
* Enjoy!!
* */
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace Security
{
class GCript
{
byte[] gKey;
byte[] gIV;
byte[] gCypher;
string gData;
RC2CryptoServiceProvider gRC2;

public GCript()
{
gRC2 = new RC2CryptoServiceProvider();
gKey = gRC2.Key;
gIV = gRC2.IV;
}
public string GEnCript(string data)
{
gData=data;

ICryptoTransform gICTP = gRC2.CreateEncryptor(this.gKey, this.gIV);
MemoryStream gMS = new MemoryStream();
CryptoStream gCS = new CryptoStream(gMS, gICTP,CryptoStreamMode.Write);

byte[] gFormat = Encoding.ASCII.GetBytes(gData);
gCS.Write(gFormat, 0, gFormat.Length);
gCS.FlushFinalBlock();
gCypher = gMS.ToArray();

return Encoding.ASCII.GetString(gMS.ToArray());
}

public string GDeCript()
{
ICryptoTransform gDCTP = gRC2.CreateDecryptor(this.gKey, this.gIV);
MemoryStream? gMS = new MemoryStream(gCypher);
CryptoStream? gCS = new CryptoStream(gMS, gDCTP, CryptoStreamMode?.Read);

byte[] gDC = new bytegCypher.Length;
gCS.Read(gDC, 0, gCypher.Length);

return Encoding.ASCII.GetString(gDC);
}

}
}

Implementation of the Bubble sorting algorithm in c#(csharp)

Implementation of the Bubble sorting algorithm, written in C#.
Source code and .exe application in the package.


CLICKHERE TO DOWNLOAD SOURCE CODE

C# Sorting Algorithms(CSharp)

In my free time i will try to add other algorithms. Theses include Shaker Sort, Comb Sort,Heap Sort ext. to learn more about Theses algorithms go to http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html


static class Sorting
{
public static void QuickSort(int[] numbers, int array_size)
{
q_sort(numbers, 0, array_size - 1);
}
private static void q_sort(int[] numbers, int left, int right)
{
int pivot, l_hold, r_hold;

l_hold = left;
r_hold = right;
pivot = numbersleft;
while (left < right)
{
while ((numbersright >= pivot) && (left < right))
right--;
if (left != right)
{
numbersleft = numbersright;
left++;
}
while ((numbersleft <= pivot) && (left < right))
left++;
if (left != right)
{
numbersright = numbersleft;
right--;
}
}
numbersleft = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
q_sort(numbers, left, pivot-1);
if (right > pivot)
q_sort(numbers, pivot+1, right);
}
public static void BubbleSort(int[] numbers, int array_size)
{
int i, j, temp;
for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (numbersj-1 > numbersj)
{
temp = numbersj-1;
numbersj-1 = numbersj;
numbersj = temp;
}
}
}
}
public static void ShellSort(int[] numbers, int array_size)
{
int i, j, increment, temp;
increment = 3;
while (increment > 0)
{
for (i=0; i < array_size; i++)
{
j = i;
temp = numbersi;
while ((j >= increment) && (numbersj-increment > temp))
{
numbersj = numbersj - increment;
j = j - increment;
}
numbersj = temp;
}
if (increment/2 != 0)
increment = increment/2;
else if (increment == 1)
increment = 0;
else
increment = 1;
}
}
public static void SelectionSort(int[] numbers, int array_size)
{
int i, j;
int min, temp;
for (i = 0; i < array_size-1; i++)
{
min = i;
for (j = i+1; j < array_size; j++)
{
if (numbersj < numbersmin)
min = j;
}
temp = numbersi;
numbersi = numbersmin;
numbersmin = temp;
}
}
public static void InsertionSort(int[] numbers, int array_size)
{
int i, j, index;
for (i=1; i < array_size; i++)
{
index = numbersi;
j = i;
while ((j > 0) && (numbersj-1 > index))
{
numbersj = numbersj-1;
j = j - 1;
}
numbersj = index;
}
}
public static void MergeSort(int[] numbers, int[] temp, int array_size)
{
m_sort(numbers, temp, 0, array_size - 1);
}
private static void m_sort(int[] numbers, int[] temp, int left, int right)
{
int mid;
if (right > left)
{
mid = (right + left) / 2;
m_sort(numbers, temp, left, mid);
m_sort(numbers, temp, mid+1, right);
merge(numbers, temp, left, mid+1, right);
}
}
private static void merge(int[] numbers, int[] temp, int left, int mid, int right)
{
int i, left_end, num_elements, tmp_pos;

left_end = mid - 1;
tmp_pos = left;
num_elements = right - left + 1;
while ((left <= left_end) && (mid <= right))
{
if (numbersleft <= numbersmid)
{
temptmp_pos = numbersleft;
tmp_pos = tmp_pos + 1;
left = left +1;
}
else
{
temptmp_pos = numbersmid;
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}
while (left <= left_end)
{
temptmp_pos = numbersleft;
left = left + 1;
tmp_pos = tmp_pos + 1;
}
while (mid <= right)
{
temptmp_pos = numbersmid;
mid = mid + 1;
tmp_pos = tmp_pos + 1;
}
for (i=0; i <= num_elements; i++)
{
numbersright = tempright;
right = right - 1;
}
}


}

how to generate random numbers in C#(CSharp).

Generating Random Numbers in the .NET Framework using C#


Random numbers may be generated in the .NET Framework by making use of the Random class. This class may be instantiated using the following code:


//Create a new Random class in C#
Random RandomClass? = new Random();

Random Integers
Once the class has been instantiated, a random integer can be obtained by calling the Next method of the Random class:


//C#
int RandomNumber? = RandomClass?.Next();

The value of RandomNumber? will, therefore, be assigned a random whole number between 1 and 2,147,483,647.

In most coding situations, it is more desirable to create a random number within a certain size range. In this case, the Next method should be called with two arguments: the minimum value and the maximum value. For example, the following assigns RandomNumber? to a value that is greater or equal to 4 and less than 14:


//C#
int RandomNumber? = RandomClass?.Next(4, 14);

Note that an ArgumentOutOfRangeException? will be raised if the minimum value is larger than the maximum value.

It is also possible to specify just the maximum value using a different constructor. The following will return a return a random integer that is greater or equal to 0 and less than 14:


//C#
int RandomNumber? = RandomClass?.Next(14);

Again, an ArgumentOutOfRangeException? will be raised if the maximum value is smaller than 0.

Random Floating Point Numbers
As well as returning random integers, the Random class can also return floating point numbers. The NextDouble? method returns a random number as a Double. The random number's value is always greater or equal to 0.0, and less than 1.0:


//Create a random double using C#
double RandomNumber? = RandomClass?.NextDouble();

Notepad program written in C#(C Sharp).




Notepad program written in C#. Will show you how to use various dialogs in C#, how to copy&paste using clipboard and without clipboards, how to use windows registry for saving default setting of notepad, printing,and how to read and write a text file.


With this project you get idea about.

1. How to use various dialogs in C#.

-For opening and saving file
-For changing Forecolor and Backcolor
-For Print-Layout? and Printing

2. How to do copy/paste using clipboard and without clipboard.(Code commented for w/o clipboard)

3. How to use windows registry for saving default setting of notepad.

4. Reading and writing text file.


CLICKHERE TO DOWNLOAD SOURCE CODE

How to create a NotePad like editor in C#(CSharp)

Here is an example of how to create a NotePad? like editor in C#. This code involves the usage of ToolBar?, StatusBar?, Menu, File Manipulation and a lot of String Functions. For this project I tried to use as many basic aspects of C# functionality as possible.



CLICKHERE TO DOWNLOAD SOURCE CODE

how to read or write (Unicode) character based data through TextReader and TextWriter in C#

INTRODUCTION:

This article covers the information of how to read or write (Unicode) character based data through TextReader? and TextWriter?. The TextReader? and TextWriter? are base classes. The StreamReader? and StringReader? derives from the abstract type TextReader?. Similarly the StreamWriter? and StringWriter? derives from the abstract type TextWriter?.

STREAMWRITERS & STREAMREADERS:

As I mentioned earlier StreamWriter? type derives from a base class named TextWriter?. This class defines members that allow derived types to write textual data to a given character stream.

Let us see some of the main members of the abstract class TextWriter?.

1.close() — Closes the Writer and frees any associated resources.
2.Write() — Writes a line to the text stream, with out a newline.
3.WriteLine() — Writes a line to the text stream, with a newline.
4.Flush() — Clears all buffers.

WRITING - TEXT FILE:

Let us see the Writing to a Text File with a example.

Before we move into writing to a text file we have to know about "FileInfo" class. What is FileInfo? In the framework of .NET , the system.IO namespace is the region of the base class libraries devoted to file-based input and output services.File Info is one of the core type of System.IO Namespace. The function of the FileInfo? is to encapsulate a number of details regarding existing files on your hard drive (size,file attributes,creating time,etc.)as well as aid in the creation and destruction of new files. Let us move to example.

In this example in the Writetextfile class I create a file named "Arungg.txt" using the FileInfo? class. After creating the text file using the CreateText() method, I get a StreamWriter? and write some textual data to the newly created text file. We can also add numeric data into the text file.


public class Writetextfile

{
public static int Main(sting[] args)
{
FileInfo t = new FileInfo("Arungg.txt");
StreamWriter Tex =t.CreateText();
Tex.WriteLine("Arungg has launced another article");
Tex.WriteLine("csharpheaven is the new url for c-sharpcorner");
Tex.Write(Tex.NewLine);
Tex.Close();
Console.WriteLine(" The Text file named Arungg is created ");
}
}

If you open the text file the data is entered there.
~~#FF0000:READING - TEXT FILE:~~

Now let us see how to read a text file using the StreamReader type.

Let us see some of the main members of the abstract class TextReader.

1.Read() -- Reads data from an input stream.
2.ReadLine() -- Reads a line of characters from the current stream and returns the data as a string.
3.ReadToEnd() -- Reads all characters to the end of the TextReader and returns them as one string.



public class Readtextfile
{
public static int Main(string[] args)
{
StreamReader? re = File.OpenText("Arungg.txt");
string input = null;
while ((input = re.ReadLine()) != null)
{
Console.WriteLine(input);
}
re.Close();
return 0;
}
}

In the above class Readtextfile I open the text file Arungg.txt and read the contents using the ReadLine() method. In both StreamReader? and StreamWriter? are concerned with moving text data to and from a specified file.

STRINGWRITERS & STRINGREADERS:

Using the StringReaders? and StringWriters? can treat textual information as a stream of in-memory characters. In this we can insert or remove string between a block of textual data. Let us see a program in which I add and delete some string between a block of text. Running the above program we get the textual data in the console.

The output:

Data:
Friendship is not a two way road.
It is a one way road travelled by two people.

Press any key to continue

Now I show you how to insert and delete some string between textual data.


using System.Text;

public class stringwrite
{
public static int Main(string[] args)
{
StringWriter? wr = new StringWriter();
wr.WriteLine("Friendship is not a two way road.");
wr.WriteLine("It is a one way road travelled by two people.");
wr.Write(Writer.NewLine);
wr.Close();

StringBuilder? bu = wr.GetStringBUilder();
string entiredata = bu.ToString();
Console.WriteLine("The data:{\n0}",entiredata);
// TO ADD SOME STRING.

bu.Insert(45,"together-hand in hand");
entiredata = bu.ToString();
Console.WriteLine("The modified data:\n{0}",entiredata);

// TO REMOVE SOME STRING.

bu.Remove(45."together-hand in hand".Length);
entiredata = bu.ToString
Console.WriteLine("The original data:\n{0}",entiredata);
return 0;
}
}

In the above program I write some character data to a StringWriter? type and modify the data by inserting some item to buffer at position 45.After inserting I also show how to remove some particular string from the data.
The Output:

The Data:
Friendship is not a two way road.
It is a one way road travelled by two people.

The modified data:
Friendship is not a two way road.
It is a one way road travelled by two people together-hand in hand.

The original data:
Friendship is not a two way road.
It is a one way road travelled by two people.

Now Let us see how to use StringReader? to read a block of character data rather than a entire file.


StringReader re = new StringReader(wr.ToString());

string input = null;
while(( input = re.ReadLine()) != null)
{
Console.Write\line(input);
}
re.Close();

Like the above way by using StringReader? we can read data from a file.

CONCLUSION:

I hope after reading this article , the user has gained some information about how to create,write and read in a text file using TextReader? and TextWriter? in C# and also something about Friendship!.

dotnet(.Net) Project Source code Downloads and Tutorials

Email Subscrption



Enter your email address:

Delivered by FeedBurner

Feedburner Count

Blog Archive

Unique Visitor

Design by araba-cı | MoneyGenerator Blogger Template by GosuBlogger