Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Article

File Server - Web Service

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

Image 1

Introduction

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:

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

A basic enumerator of files extensions:

VB
Public Enum FileExtensions
        htm
        html
        asp
        aspx
        jpg
        gif
        dll
        exe
        all
End Enum

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

VB
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:

VB
<!--<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
        Next
        Return aFiles
End Function

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

VB
Private Shared Function ReadFile(ByVal FilePath As String) As Byte()
        Dim fs As FileStream
        Try
            ' 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
        Finally
            If Not fs Is Nothing Then
                fs.Close()
            End If
        End Try
End Function

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

VB
<!--<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
        Try
            objFstream = File.Open(WebServerPath & VirtualPath & "\" & _
                                Name, FileMode.Create, FileAccess.Write)
            Dim lngLen As Long = Content.Length
            objFstream.Write(Content, 0, CInt(lngLen))
            objFstream.Flush()
            objFstream.Close()
            Return True
        Catch exc As System.UnauthorizedAccessException
            Return False
        Catch exc As Exception
            Return False
        Finally
            If Not objFstream Is Nothing Then
                objFstream.Close()
            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.

VB
Imports System.IO

Add some private variables:

VB
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:

VB
Public Function SaveFile(ByVal Name As String, _
                           ByVal Content As Byte()) As Boolean
        Dim objFstream As FileStream
        Try
            objFstream = File.Open(SaveFilePath & Name, _ 
                            FileMode.Create, FileAccess.Write)
            Dim lngLen As Long = Content.Length
            objFstream.Write(Content, 0, CInt(lngLen))
            objFstream.Flush()
            Return True
        Catch exp As Exception
            Return False
        Finally
            objFstream.Close()
        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:

VB
Sub Main()
        Try
            mWSFileServer = New WSFileServer.FileServer()
            mFileInformation = mWSFileServer.Browse("/ProgramGuide", _
                                     WSFileServer.FileExtensions.aspx)
            Dim i As Integer
            For i = 0 To mFileInformation.Length - 1
                With mFileInformation(i)
                    Console.WriteLine(mBar.ToString())
                    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)
                    Else
                        Console.WriteLine("Save file failure!")
                    End If
                End With
            Next
            Console.WriteLine(mBar.ToString())
            Console.Read()
        Catch exp As Exception
            Console.WriteLine(mBar)
        Finally
            mWSFileServer.Dispose()
        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 ;-)

History

  • 2/18/2003 - First release.

License

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
Brazil

Comments and Discussions

 
Generalok article Pin
Donsw22-Nov-09 14:19
Donsw22-Nov-09 14:19 
GeneralPermission to public Pin
subramanya198327-Apr-08 20:34
subramanya198327-Apr-08 20:34 
GeneralRe: Permission to public Pin
Ricardo Martins28-Apr-08 5:30
Ricardo Martins28-Apr-08 5:30 
GeneralThank You for this great article [modified] Pin
Yaagoub20-Sep-07 10:37
Yaagoub20-Sep-07 10:37 
GeneralUpload Doesn't Work Pin
jtokach25-Apr-07 8:27
jtokach25-Apr-07 8:27 
QuestionWant to upload my text file to local server using vs .net console application Pin
sonimitu2-Apr-07 19:12
sonimitu2-Apr-07 19:12 
GeneralUpload Problem Pin
all4it19-Dec-06 8:05
all4it19-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
Ricardo Martins8-Jun-09 14:08 
GeneralTransfering large files Pin
Nigel-Findlater20-Jan-05 3:11
Nigel-Findlater20-Jan-05 3:11 
GeneralUpload Function Pin
okantekeli15-Feb-04 22:43
okantekeli15-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
Chris Keeble6-Jan-04 6:34 
GeneralWSFileServer.FileExtensions.aspx Pin
Anonymous11-Dec-03 9:47
Anonymous11-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
Ricardo Martins9-Dec-03 13:32 
QuestionAre there practical limitations to file size? Pin
Jeff Weiss19-Nov-03 11:59
Jeff Weiss19-Nov-03 11:59 
AnswerRe: Are there practical limitations to file size? Pin
Thomas-H.26-Oct-05 5:13
Thomas-H.26-Oct-05 5:13 
Questionwhat about the upload method? Pin
VinhV2-Oct-03 8:50
VinhV2-Oct-03 8:50 
Can you please give example on how to implement on uploading method?? Thanks.
Generalupload function Pin
guru3721-Apr-03 23:12
guru3721-Apr-03 23:12 
Generalupload function Pin
guru3721-Apr-03 23:08
guru3721-Apr-03 23:08 
QuestionHow about retries or resuming? Pin
Matt Philmon24-Feb-03 5:07
Matt Philmon24-Feb-03 5:07 
AnswerRe: How about retries or resuming? Pin
Ricardo Martins26-Feb-03 0:17
Ricardo Martins26-Feb-03 0:17 
GeneralRe: How about retries or resuming? Pin
Nigel-Findlater20-Jan-05 3:01
Nigel-Findlater20-Jan-05 3:01 
GeneralSome ideas Pin
Jan Tielens23-Feb-03 20:45
Jan 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.