Click here to Skip to main content
15,443,018 members
Articles / Web Development / ASP.NET
Posted 22 Feb 2003


143 bookmarked

File Server - Web Service

Rate me:
Please Sign up or sign in to vote.
4.67/5 (33 votes)
22 Feb 20032 min read
Get and put files in your web server using Web Services

Image 1


This article shows how to use Web Services to create a service to manage (put and get) files in your Web Server using HTTP protocol.

If you don't have a physical access to the web server or just for sharing your web server content like pictures or files, this web service can be really useful and fast.

The code

So, let's stop talking and go to the code : )

First we need to import extra classes:

Imports System.Web.Services
Imports System.Configuration
Imports System.IO

A basic enumerator of files extensions:

Public Enum FileExtensions
End Enum

The class FileInformation will be populated with information about each file.

Public Class FileInformation
        Public Name As String
        Public Size As Long
        Public CreadedDate As DateTime
        Public LastModified As DateTime
        Public LastAccess As DateTime
        Public FileType As String
        Public FileLocation As String
        Public FileContent As Byte()
End Class

The WebMethod Browse will return an array of FileInformation class:

<!--<WebMethod(Description:="Retrieve an array of files 
                      with name, attributes and content.")> _-->
Public Function Browse(ByVal VirtualPath As String, ByVal FileExtension _
                       As FileExtensions) As FileInformation()
        Dim i As Integer
        Dim fi As FileInfo
        Dim aFiles As FileInformation()
        Dim mExtension As String
        Select Case FileExtension
            Case FileExtensions.asp
                mExtension = "asp"
            Case FileExtensions.aspx
                mExtension = "aspx"
            Case FileExtensions.gif
                mExtension = "gif"
            Case FileExtensions.htm
                mExtension = "htm"
            Case FileExtensions.html
                mExtension = "html"
            Case FileExtensions.jpg
                mExtension = "jpg"
            Case FileExtensions.dll
                mExtension = "dll"
            Case FileExtensions.exe
                mExtension = "exe"
            Case FileExtensions.all
                mExtension = "*"
        End Select

        Dim di As New DirectoryInfo(WebServerPath & VirtualPath)
        Dim afi As FileInfo() = _
         di.GetFiles("*." & mExtension)

        ReDim Preserve aFiles(afi.Length - 1)

        For Each fi In afi
            aFiles(i) = New FileInformation()
            aFiles(i).Name = fi.Name
            aFiles(i).Size = fi.Length
            aFiles(i).LastAccess = fi.LastAccessTime
            aFiles(i).CreadedDate = fi.CreationTime
            aFiles(i).LastModified = fi.LastWriteTime
            aFiles(i).FileType = fi.Extension
            aFiles(i).FileLocation = fi.DirectoryName
            aFiles(i).FileContent = ReadFile(WebServerPath & _
                                     VirtualPath & "\" & fi.Name)
            i += 1
        Return aFiles
End Function

The Private Shared method ReadFile returns a byte() with the file content:

Private Shared Function ReadFile(ByVal FilePath As String) As Byte()
        Dim fs As FileStream
            ' Read file and return contents
            fs = File.Open(FilePath, FileMode.Open, FileAccess.Read)
            Dim lngLen As Long = fs.Length
            Dim abytBuffer(CInt(lngLen - 1)) As Byte
            fs.Read(abytBuffer, 0, CInt(lngLen))
            Return abytBuffer
        Catch exp As Exception
            Return Nothing
            If Not fs Is Nothing Then
            End If
        End Try
End Function

UploadFile WebMethod is used to send a single file to the web server:

<!--<WebMethod(Description:="Upload a single file to
                                                 web server.")> _-->
Public Function UploadFile(ByVal VirtualPath As String, _
           ByVal Name As String, ByVal Content As Byte()) As Boolean
        Dim objFile As File, objStream As StreamWriter, _
                                 objFstream As FileStream
            objFstream = File.Open(WebServerPath & VirtualPath & "\" & _
                                Name, FileMode.Create, FileAccess.Write)
            Dim lngLen As Long = Content.Length
            objFstream.Write(Content, 0, CInt(lngLen))
            Return True
        Catch exc As System.UnauthorizedAccessException
            Return False
        Catch exc As Exception
            Return False
            If Not objFstream Is Nothing Then
            End If
        End Try
End Function

The WSFileServer has another two useful methods called DirectoryExists and FileExists.

Using the code

There is a simple console application to retrieve a list of files. First create a new console application project and add a Web Reference to that:

Image 2

Image 3

Now add an import to System.IO class, we need that for the save file method.

Imports System.IO

Add some private variables:

Private mWSFileServer As WSFileServer.FileServer
Private mFileInformation() As WSFileServer.FileInformation
Private mBar As New String("-", 50)
Public Const SaveFilePath As String = "C:\Temp\"

Now we'll create a method to save the file content, receiving the filename and file content:

Public Function SaveFile(ByVal Name As String, _
                           ByVal Content As Byte()) As Boolean
        Dim objFstream As FileStream
            objFstream = File.Open(SaveFilePath & Name, _ 
                            FileMode.Create, FileAccess.Write)
            Dim lngLen As Long = Content.Length
            objFstream.Write(Content, 0, CInt(lngLen))
            Return True
        Catch exp As Exception
            Return False
        End Try
End Function

The Sub Main method will initialize the file server Web service and show each file's specified web server virtual path:

Sub Main()
            mWSFileServer = New WSFileServer.FileServer()
            mFileInformation = mWSFileServer.Browse("/ProgramGuide", _
            Dim i As Integer
            For i = 0 To mFileInformation.Length - 1
                With mFileInformation(i)
                    Console.WriteLine("File: {0}", .Name)
                    Console.WriteLine("Size: {0}", .Size)
                    Console.WriteLine("Location: {0}", .FileLocation)
                    Console.WriteLine("LastModified: {0}", .LastModified)
                    Console.WriteLine("CreateDate: {0}", .CreadedDate)
                    Console.WriteLine("LastAccess: {0}", .LastAccess)
                    If SaveFile(.Name, .FileContent) Then
                        Console.WriteLine("File saved sucessfull at:{0}", _
                                                   SaveFilePath & .Name)
                        Console.WriteLine("Save file failure!")
                    End If
                End With
        Catch exp As Exception
        End Try
End Sub

The result of the web service call can be seen in the following screen:

Image 4

Console application calls the Browser method of the web service, displays all files information and saves it.

Image 5

Points of interest

I think that when you use Web Services technology, there are no limits for your applications, you just need to be creative ;-)


  • 2/18/2003 - First release.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Written By
Architect Sky Brasil
Brazil Brazil
Ricardo Martins
.NET Architect

Comments and Discussions

Generalok article Pin
Donsw22-Nov-09 14:19
MemberDonsw22-Nov-09 14:19 
Ok article especially written in 2003

My Recent Article : CDC - Change Data Capture

GeneralPermission to public Pin
subramanya198327-Apr-08 20:34
Membersubramanya198327-Apr-08 20:34 
GeneralRe: Permission to public Pin
Ricardo Martins28-Apr-08 5:30
MemberRicardo Martins28-Apr-08 5:30 
GeneralThank You for this great article [modified] Pin
Yaagoub20-Sep-07 10:37
MemberYaagoub20-Sep-07 10:37 
GeneralUpload Doesn't Work Pin
jtokach25-Apr-07 8:27
Memberjtokach25-Apr-07 8:27 
QuestionWant to upload my text file to local server using vs .net console application Pin
sonimitu2-Apr-07 19:12
Membersonimitu2-Apr-07 19:12 
GeneralUpload Problem Pin
all4it19-Dec-06 8:05
Memberall4it19-Dec-06 8:05 
QuestionHow about C# Version {Please} Pin
| Muhammad Waqas Butt |28-Apr-06 1:02
professional| Muhammad Waqas Butt |28-Apr-06 1:02 
AnswerRe: How about C# Version {Please} Pin
Ricardo Martins8-Jun-09 14:08
MemberRicardo Martins8-Jun-09 14:08 
GeneralTransfering large files Pin
Nigel-Findlater20-Jan-05 3:11
MemberNigel-Findlater20-Jan-05 3:11 
GeneralUpload Function Pin
okantekeli15-Feb-04 22:43
Memberokantekeli15-Feb-04 22:43 
GeneralRe: Upload Function Pin
Shawn Carr30-Apr-04 7:41
sussShawn Carr30-Apr-04 7:41 
GeneralCall the webservice from an HTML form Pin
Chris Keeble6-Jan-04 6:34
MemberChris Keeble6-Jan-04 6:34 
GeneralWSFileServer.FileExtensions.aspx Pin
Anonymous11-Dec-03 9:47
MemberAnonymous11-Dec-03 9:47 
GeneralBinary Uploader Pin
Luis Botero9-Dec-03 3:57
sussLuis Botero9-Dec-03 3:57 
GeneralRe: Binary Uploader Pin
Ricardo Martins9-Dec-03 13:32
MemberRicardo Martins9-Dec-03 13:32 
QuestionAre there practical limitations to file size? Pin
Jeff Weiss19-Nov-03 11:59
MemberJeff Weiss19-Nov-03 11:59 
AnswerRe: Are there practical limitations to file size? Pin
Thomas-H.26-Oct-05 5:13
MemberThomas-H.26-Oct-05 5:13 
Questionwhat about the upload method? Pin
VinhV2-Oct-03 8:50
MemberVinhV2-Oct-03 8:50 
Generalupload function Pin
guru3721-Apr-03 23:12
Memberguru3721-Apr-03 23:12 
Generalupload function Pin
guru3721-Apr-03 23:08
Memberguru3721-Apr-03 23:08 
QuestionHow about retries or resuming? Pin
Matt Philmon24-Feb-03 5:07
MemberMatt Philmon24-Feb-03 5:07 
AnswerRe: How about retries or resuming? Pin
Ricardo Martins26-Feb-03 0:17
MemberRicardo Martins26-Feb-03 0:17 
GeneralRe: How about retries or resuming? Pin
Nigel-Findlater20-Jan-05 3:01
MemberNigel-Findlater20-Jan-05 3:01 
GeneralSome ideas Pin
Jan Tielens23-Feb-03 20:45
MemberJan Tielens23-Feb-03 20:45 

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.