theDeSilva.com Andrew de Silva

Save File Stream using VB.NET

January 4th, 2010 · No Comments · .NET

Here is a simple VB.NET that would allow you to post a file stream from Flex. The class below saves the file into a location on your server. To use it you can simply use HTTP POST and pass in the directory save location using the query string dir. I used a catch try block to log all error since I’m streaming this and will not see the error. You will find the code to the error logging here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
Imports System
Imports System.IO
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
 
 
Partial Class FlexUpload
    Inherits System.Web.UI.Page
 
    Private filePath As String
    Private fileStream As FileStream
    Private streamWriter As StreamWriter
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim fileName As String
        Dim dir As String = Request.QueryString("dir")
 
        Dim saveToFolder As String = "C:\" & dir & "\"
 
        If File.Exists(saveToFolder) Then
            File.Delete(saveToFolder)
        End If
 
        If Directory.Exists(saveToFolder) Then
            ' do nothing directory exist
        Else
            Directory.CreateDirectory(saveToFolder)
        End If
 
        Try
            Dim i As Integer
 
            For i = 0 To Request.Files.Count - 1
                fileName = System.IO.Path.GetFileName(Request.Files(i).FileName)
                Request.Files(i).SaveAs(saveToFolder & fileName)
            Next
 
        Catch ex As Exception
            WriteLog("Error :" & DateTime.Now & " " & ex.Message)
        End Try
 
    End Sub
 
    ' Error Logging Functions 
     Public Sub OpenFile()
        Dim strPath As String
        strPath = MapPath("~") & "\Error.log"
        If System.IO.File.Exists(strPath) Then
            fileStream = New FileStream(strPath, FileMode.Append, FileAccess.Write)
        Else
            fileStream = New FileStream(strPath, FileMode.Create, FileAccess.Write)
        End If
        StreamWriter = New StreamWriter(fileStream)
    End Sub
 
    Public Sub WriteLog(ByVal strComments As String)
        OpenFile()
        StreamWriter.WriteLine(strComments)
        CloseFile()
    End Sub
 
    Public Sub CloseFile()
        StreamWriter.Close()
        fileStream.Close()
    End Sub
 
End Class
Share and Enjoy:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Reddit
  • Technorati
  • Facebook
  • Google Bookmarks
  • LinkedIn

Tags: