Create your own Web Server using C#

The Code

Let us dive into the code...

// MyWebServer Written by Imtiaz Alam
namespace Imtiaz 
{

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading ;

class MyWebServer 
{

    private TcpListener myListener ;
    private int port = 5050 ;  // Select any free port you wish 
    //The constructor which make the TcpListener start listening on the
    //given port. It also calls a Thread on the method StartListen(). 

    public MyWebServer()
    {
        try
        {
            //start listing on the given port
            myListener = new TcpListener(port) ;
            myListener.Start();
            Console.WriteLine("Web Server Running... Press ^C to Stop...");
            
            //start the thread which calls the method 'StartListen'
            Thread th = new Thread(new ThreadStart(StartListen));
            th.Start() ;

        }
        catch(Exception e)
        {
            Console.WriteLine("An Exception Occurred while Listening :" +e.ToString());
        }
    }

We defined namespace, included the references required in our application and initialized the port in the constructor, started the listener and created a new thread and called startlisten function.

Now let us assume that the user does not supplies the file name, in that case we have to identify the default filename and send to the browser, as in IIS we define the default document under documents tab.

We have already stored the default file name in the default.dat and stored in the data directory. The GetTheDefaultFileName function takes the directory path as input, open the default.dat file and looks for the file in the directory provided and returns the file name or blank depends on the situation.

public string GetTheDefaultFileName(string sLocalDirectory)
{
    StreamReader sr;
    String sLine = "";

    try
    {
        //Open the default.dat to find out the list
        // of default file
        sr = new StreamReader("data\\Default.Dat");

        while ((sLine = sr.ReadLine()) != null)
        {
            //Look for the default file in the web server root folder
            if (File.Exists( sLocalDirectory + sLine) == true)
                break;
        }
    }
    catch(Exception e)
    {
        Console.WriteLine("An Exception Occurred : " + e.ToString());
    }
    if (File.Exists( sLocalDirectory + sLine) == true)
        return sLine;
    else
        return "";
}

We also need to resolve the virtual directory to the actual physical directory like we do in IIS. We have already stored the mapping between the Actual and Virtual directory in Vdir.Dat. Remember in all the cases the file format is very important.


public string GetLocalPath(string sMyWebServerRoot, string sDirName)
{

    StreamReader sr;
    String sLine = "";
    String sVirtualDir = ""; 
    String sRealDir = "";
    int iStartPos = 0;


    //Remove extra spaces
    sDirName.Trim();



    // Convert to lowercase
    sMyWebServerRoot = sMyWebServerRoot.ToLower();

    // Convert to lowercase
    sDirName = sDirName.ToLower();

    
    try
    {
        //Open the Vdirs.dat to find out the list virtual directories
        sr = new StreamReader("data\\VDirs.Dat");

        while ((sLine = sr.ReadLine()) != null)
        {
            //Remove extra Spaces
            sLine.Trim();

            if (sLine.Length > 0)
            {
                //find the separator
                iStartPos = sLine.IndexOf(";");

                // Convert to lowercase
                sLine = sLine.ToLower();

                sVirtualDir = sLine.Substring(0,iStartPos);
                sRealDir = sLine.Substring(iStartPos + 1);

                if (sVirtualDir == sDirName)
                {
                    break;
                }
            }
        }
    }
    catch(Exception e)
    {
        Console.WriteLine("An Exception Occurred : " + e.ToString());
    }


    if (sVirtualDir == sDirName)
        return sRealDir;
    else
        return "";
}

You might also like...

Comments

About the author

Imtiaz Alam United States

Imtiaz Alam is a Senior Developer, currently residing in Phoenix, Arizona. He has more than five years of development experience in developing Mirosoft based Solution.

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“XML is like violence - if it's not working for you, you're not using enough of it.”