Click here to Skip to main content
13,556,972 members
Click here to Skip to main content
Add your own
alternative version


66 bookmarked
Posted 17 Jan 2008
Licenced CPOL

Upload Any File Type through a Web Service

, 23 Jan 2008
Rate this:
Please Sign up or sign in to vote.
This article shall describe an approach that may be used to upload any sort of a file through a web service from a Windows Forms application.


This article shall describe an approach that may be used to upload any sort of file through a web service from a Windows Forms application. The approach demonstrated does not rely on the ASP.NET file uploader control and allows the developer the opportunity to upload files programmatically and without user intervention. Such an approach may be useful for doing something like processing out the contents of a local message queue when an internet service is available (if the user base were mobile and had only intermittent connectivity). The article also addresses the use of a file size check as a precursor to allowing a file to upload through the service.


Figure 1: Test application shown uploading a file


Figure 2: Mixed bag of different file types in transient storage folder

Getting Started

The solution contains two projects: one is an ASP.NET Web Service project (Uploader) and the other is a Windows Forms test application (TestUploader) used to demonstrate uploading files through the web method provided in the web service project.

The web service project contains only a single web service (FileUploader) which in turn contains only a single web method (UploadFile). The Windows Forms application contains only a single form which contains the controls (one textbox and two buttons used in conjunction with an OpenFileDialog control) and the code necessary to select and upload files through the web service.


Figure 3: Solution Explorer with the both projects visible

Code: Uploader Web Service Project

The Uploader web service project is an ASP.NET web service project containing a single web service called FileUploader. This web service exposes a single web method called UploadFile. The code for this web service begins with the following:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.IO;

namespace Uploader
    /// <span class="code-SummaryComment"><summary></span>
    /// This web method will provide an web method to load any
    /// file onto the server; the UploadFile web method
    /// will accept the report and store it in the local file system.
    /// <span class="code-SummaryComment"></summary></span>
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class FileUploader : System.Web.Services.WebService

The class starts out with the default imports. I added System.IO to the defaults to support the use of file and memory streams. The web service namespace is left as the default, which of course will have to be updated if the service were deployed.

The remainder of the code supplied in this class is used to define the web method used to upload the file; the code is annotated. The essential process is that files converted to byte arrays are passed along with the full name of the file (not the path), including the extension as arguments, to the UploadFile web method. The byte array is passed to a memory stream, and a file stream is opened pointing to a newly created file (named the name of the original file) within the target folder used to store the files. Once the file stream has been created, the memory stream is written into the file stream and then the memory stream and file stream are disposed of.

The web method is set up to return a string. If all goes well, the string returned will read, “OK.” If not, the error message encountered will be returned to the caller.

        public string UploadFile(byte[] f, string fileName)
            // the byte array argument contains the content of the file
            // the string argument contains the name and extension
            // of the file passed in the byte array
                // instance a memory stream and pass the
                // byte array to its constructor
                MemoryStream ms = new MemoryStream(f);
                // instance a filestream pointing to the
                // storage folder, use the original file name
                // to name the resulting file
                FileStream fs = new FileStream
                    ("~/TransientStorage/") +
                    fileName, FileMode.Create);
                // write the memory stream containing the original
                // file as a byte array to the filestream
                // clean up
                // return OK if we made it this far
                return "OK";
            catch (Exception ex)
                // return the error message if the operation fails
                return ex.Message.ToString();

Code: Test Uploader Windows Forms Application

The test application contains a single Windows Forms class. This form contains a text box used to display the name of the file selected for upload, a browse button to launch an open file dialog box that is used to navigate to and select a file for upload, and an upload button which is used to pass the file to the web service so that the selected file may be stored on the server. The code for this class begins with the following:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace TestUploader
    /// <span class="code-SummaryComment"><summary></span>
    /// A test form used to upload a file from a windows application using
    /// the Uploader Web Service
    /// <span class="code-SummaryComment"></summary></span>
    public partial class Form1 : Form
        public Form1()
        private void Form1_Load(object sender, EventArgs e)
            // do nothing

Aside from the default imports, I have added only System.IO to the list, this being necessary to support working with files. The namespace and class declarations are in the default configuration. In addition to System.IO, the project also adds in a web reference pointing to the File Uploader web service. The reference is given the alias of Uploader.

The next bit of code in the class is a private method used to prepare the file for submittal to the web service and to actually make that submittal. The code below is annotated to describe the activity, but the essential parts of the operation are to check the file size to see if the web service will accept the file and to convert the file to a byte array. By default, the web server will accept uploads smaller than 4 MB in size; the web.config file must be updated in order to support larger uploads.

When everything is ready, the byte array and the name of the file, including the extension, is passed to an instance of the web service web method. Note that when setting up the demo, you will have remove and add the web reference back into the project in order for it to work for you.

/// <span class="code-SummaryComment"><summary></span>
/// Upload any file to the web service; this function may be
/// used in any application where it is necessary to upload
/// a file through a web service
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="filename">Pass the file path to upload</param></span>
private void UploadFile(string filename)
        // get the exact file name from the path
        String strFile = System.IO.Path.GetFileName(filename);

        // create an instance fo the web service
        TestUploader.Uploader.FileUploader srv = new

        // get the file information form the selected file
        FileInfo fInfo = new FileInfo(filename);

        // get the length of the file to see if it is possible
        // to upload it (with the standard 4 MB limit)
        long numBytes = fInfo.Length;
        double dLen = Convert.ToDouble(fInfo.Length / 1000000);

        // Default limit of 4 MB on web server
        // have to change the web.config to if
        // you want to allow larger uploads
        if (dLen < 4)
            // set up a file stream and binary reader for the
            // selected file
            FileStream fStream = new FileStream(filename,
            FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fStream);

            // convert the file to a byte array
            byte[] data = br.ReadBytes((int)numBytes);

            // pass the byte array (file) and file name to the web
            string sTmp = srv.UploadFile(data, strFile);

            // this will always say OK unless an error occurs,
            // if an error occurs, the service returns the error
            MessageBox.Show("File Upload Status: " + sTmp, "File
            // Display message if the file was too large to upload
            MessageBox.Show("The file selected exceeds the size limit
            for uploads.", "File Size");
    catch (Exception ex)
        // display an error message to the user
        MessageBox.Show(ex.Message.ToString(), "Upload Error");

Following the UploadFile method, the next bit of code is used to handle the browse button’s click event. This code is used merely to display an open file dialog to the user and to take the file selected through that dialog and display the file name in the form’s file name text box.

/// <span class="code-SummaryComment"><summary></span>
/// Allow the user to browse for a file
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnBrowse_Click(object sender, EventArgs e)
    openFileDialog1.Title = "Open File";
    openFileDialog1.Filter = "All Files|*.*";
    openFileDialog1.FileName = "";

        openFileDialog1.InitialDirectory = "C:\\Temp";
        // skip it


    if (openFileDialog1.FileName == "")
        txtFileName.Text = openFileDialog1.FileName;


The class wraps up with the button click event handler for the upload button. This handler merely checks for text in the file name text box and, if something is there, it sends the value to the Upload method.

/// <span class="code-SummaryComment"><summary></span>
/// If the user has selected a file, send it to the upload method,
/// the upload method will convert the file to a byte array and
/// send it through the web service
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnUpload_Click(object sender, EventArgs e)
    if (txtFileName.Text != string.Empty)
        MessageBox.Show("You must select a file first.", "No File

That wraps up all of the client- and server-side code necessary to upload any sort of file to a server from a Windows Forms application.


This article was intended to demonstrate an easy approach to uploading any sort of a file to a web server from a Windows Forms application. This example uses the default upload size of 4096 KB. If you need to upload larger files, you will need to alter this value by changing the httpRuntime maxRequestLength property to the desired value. At the same time, you may need to increase the executionTimeout property to a greater value as well in order to support longer upload times. Take care when altering the values, as Microsoft has established the default 4 MB limit to provide some safety against attempts to upload extremely large files that may hamper access to the server.


  • 17 January, 2008 -- Original version posted


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

NewsCopy of this article Pin
awaneesh jatrana15-Sep-16 1:21
memberawaneesh jatrana15-Sep-16 1:21 
GeneralRe: Copy of this article - by the same author. Pin
OriginalGriff15-Sep-16 1:24
protectorOriginalGriff15-Sep-16 1:24 
GeneralHi the article is really good one Pin
geetha naidu12-Sep-08 21:55
membergeetha naidu12-Sep-08 21:55 
GeneralNice... but... Pin
David Moring22-Jan-08 13:07
memberDavid Moring22-Jan-08 13:07 
Answernice but... Pin
Amrykid17-Jan-08 13:57
memberAmrykid17-Jan-08 13:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01-2016 | 2.8.180515.1 | Last Updated 23 Jan 2008
Article Copyright 2008 by salysle
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid