DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • DGS GraphQL and Spring Boot
  • Auto-Instrumentation in Azure Application Insights With AKS
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Security by Design: Building Full-Stack Applications With DevSecOps
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • How GitHub Copilot Helps You Write More Secure Code

How to: File Sharing Application in C#

By 
Ayobami Adewole user avatar
Ayobami Adewole
·
Jun. 07, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
24.2K Views

Join the DZone community and get the full member experience.

Join For Free
This is a sequel to my blog post on "A Client Server File Sharing Application in C#" I have received several emails asking for the application to be made into a whole package instead of having it as a separate client and server applications. In order to save time and not to send the solution as email to people again, I have decided to make it a blog post and make the whole package available.

The application is written in C# and it will allow files to be sent from one computer to another on the network. It attempts to compile what both the client and server applications in my previous post- A Client Server File Sharing Application in C# do into a single project. To gain a full understanding of the workings, I recommend you read the following-

The full listing of the source code is below.
using System;;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileSharingApp
{
    public partial class Form1 : Form
    {
        private static string shortFileName = "";
        private static string fileName = "";

         public delegate void FileRecievedEventHandler(object source, 

          string fileName);

        public event FileRecievedEventHandler NewFileRecieved;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.NewFileRecieved+=new FileRecievedEventHandler

            (Form1_NewFileRecieved);
        }

        private void Form1_NewFileRecieved(object sender, string 

         fileName)
        {
            this.BeginInvoke(
            new Action(
            delegate()
            {
                MessageBox.Show("New File Recieved\n"+fileName);
                System.Diagnostics.Process.Start("explorer", @"c:\");
            }));
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            int port = int.Parse(txtHost.Text);
            Task.Factory.StartNew(() => HandleIncomingFile(port));
            MessageBox.Show("Listening on port"+port);
        }

        public void HandleIncomingFile(int port)
        {
          try
            {
                TcpListener tcpListener = new TcpListener(port);
                tcpListener.Start();
                while (true)
                {
                  Socket handlerSocket = tcpListener.AcceptSocket();
                    if (handlerSocket.Connected)
                    {
                     string fileName = string.Empty;
                     NetworkStream networkStream = new NetworkStream

                      (handlerSocket);
                     int thisRead = 0;
                     int blockSize = 1024;
                     Byte[] dataByte = new Byte[blockSize];
                     lock (this)
                     {
                      string folderPath = @"c:\";
                      handlerSocket.Receive(dataByte);
                      int fileNameLen = BitConverter.ToInt32(dataByte,

                       0);
                      fileName = Encoding.ASCII.GetString(dataByte, 4, 

                       fileNameLen);
                      Stream fileStream = File.OpenWrite(folderPath + 

                       fileName);
                      fileStream.Write(dataByte, 4+fileNameLen,(

                       1024-(4+fileNameLen)));
                      while (true)
                      {
                       thisRead = networkStream.Read(dataByte, 0, 

                        blockSize);
                       fileStream.Write(dataByte, 0,thisRead);
                       if (thisRead == 0)
                        break;
                      }
                      fileStream.Close();

                    }
                    if (NewFileRecieved != null)
                     {
                       NewFileRecieved(this, fileName);
                     }
                    handlerSocket = null;
                    }
                }

            }
            catch
            {

            }
        }

         private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "File Sharing Client";
            dlg.ShowDialog();
            txtFile.Text = dlg.FileName;
            fileName = dlg.FileName;
            shortFileName = dlg.SafeFileName;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string ipAddress = txtIPAddress.Text;
            int port = int.Parse(txtPort.Text);
            string fileName = txtFile.Text;
            Task.Factory.StartNew(() => SendFile(ipAddress,port,

             fileName,shortFileName));
            MessageBox.Show("File Sent");
        }

        public void SendFile(string remoteHostIP, int remoteHostPort

           , string  longFileName, string shortFileName)
        {
         try
         {
          if(!string.IsNullOrEmpty(remoteHostIP)) 

          { 

            byte[] fileNameByte = Encoding.ASCII.GetBytes

             (shortFileName); byte[] fileData =

              File.ReadAllBytes(longFileName); 

             byte[] clientData
                 = new byte[4 + fileNameByte.Length 

                + fileData.Length]; 

             byte[] fileNameLen = BitConverter.GetBytes(

              fileNameByte.Length); 

             fileNameLen.CopyTo(clientData, 0); 

             fileNameByte.CopyTo(clientData,4);

             fileData.CopyTo(clientData, 4 + fileNameByte.Length);

            TcpClient clientSocket = new TcpClient(remoteHostIP,

           remoteHostPort);

             NetworkStream networkStream = clientSocket.GetStream(); 

          networkStream.Write(clientData,
                  0, clientData.GetLength

              (0)); networkStream.Close(); }
         }
         catch
         {

         }
        }
    }
}    

 The Complete source code of the application is available for download Here
application csharp

Published at DZone with permission of Ayobami Adewole, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • DGS GraphQL and Spring Boot
  • Auto-Instrumentation in Azure Application Insights With AKS
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!