Click here to Skip to main content
12,406,795 members (54,424 online)
Click here to Skip to main content
Add your own
alternative version

Stats

276.5K views
6.2K downloads
139 bookmarked
Posted

File Server - Web Service

, 22 Feb 2003
Rate this:
Please Sign up or sign in to vote.
Get and put files in your web server using Web Services

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:

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

A basic enumerator of files extensions:

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.

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

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

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

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:

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

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 Wink | ;-)

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

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
Generalok article Pin
Donsw22-Nov-09 14:19
memberDonsw22-Nov-09 14:19 
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
member| 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
kcl6-Jan-04 6:34
memberkcl6-Jan-04 6:34 
GeneralWSFileServer.FileExtensions.aspx Pin
Anonymous11-Dec-03 9:47
sussAnonymous11-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
jweiss19-Nov-03 11:59
memberjweiss19-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
vinhvu2-Oct-03 8:50
sussvinhvu2-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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160730.1 | Last Updated 23 Feb 2003
Article Copyright 2003 by Ricardo Martins
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid