#Region " Imports " Imports System.IO Imports Sps.Security Imports System.Text.RegularExpressions Imports Sps.AppException Imports System.xml.Serialization #End Region Public Class Fso #Region " Instance Fields " Shared _fileBaseName As String = String.Empty 'Declare base location of file store. 'NOTE: Write permission must be granted to "AUTHENTICATED_USERS" for this folder. Shared _documentBase As String = HttpContext.Current.Server.MapPath("/statistics/UPLOAD/") Shared _fileExtension As String = String.Empty Shared _fileHash As String = String.Empty Shared _fileLength As Integer = 0 Shared _fileMimetype As String = String.Empty Shared _fileName As String = String.Empty Shared _filePathName As String = String.Empty Shared _invalidFileType As String = String.Empty Shared _isBinaryFile As Boolean = False #End Region #Region " Enumerations " Public Enum fileType As Integer cs csv doc docx gif htm html invalid jpg js mpp pdf png pps ppt pptx rtf tif txt vb xls xlsx xml zip End Enum #End Region #Region " Properties " Public Shared ReadOnly Property baseName() As String Get Return _fileBaseName End Get End Property Public Shared Property documentBase() As String 'Note: value passed in should look like "\directory\" Get Return _documentBase End Get Set(ByVal value As String) _documentBase = HttpContext.Current.Server.MapPath("..") & value End Set End Property Public Shared ReadOnly Property extension() As String Get Return _fileExtension End Get End Property Public Shared ReadOnly Property hash() As String Get Return _fileHash End Get End Property Public Shared ReadOnly Property length() As Integer Get Return _fileLength End Get End Property Public Shared ReadOnly Property mimetype() As String Get Return _fileMimetype End Get End Property Public Shared ReadOnly Property name() As String Get Return _fileName End Get End Property Public Shared ReadOnly Property pathName() As String Get Return _filePathName End Get End Property Public Shared ReadOnly Property isBinaryFile() As Boolean Get Return _isBinaryFile End Get End Property #End Region #Region " Methods " 'Method converts fileType as a string to fileType as an enumerated type: ' First argument "fileType" specifies the fileType to convert. ' Returns the associated fileType from the fileType enum. Public Shared Function ConvertFileType(ByVal fileType As String) As Fso.fileType Select Case LCase(fileType) Case "cs" Return Fso.fileType.cs Case "csv" Return Fso.fileType.csv Case ("doc") Return Fso.fileType.doc Case "docx" Return Fso.fileType.docx Case "gif" Return Fso.fileType.gif Case "htm" Return Fso.fileType.htm Case "html" Return Fso.fileType.html Case "jpg" Return Fso.fileType.jpg Case "js" Return Fso.fileType.js Case "mpp" Return Fso.fileType.mpp Case "pdf" Return Fso.fileType.pdf Case "png" Return Fso.fileType.png Case "pps" Return Fso.fileType.pps Case "ppt" Return Fso.fileType.ppt Case "pptx" Return Fso.fileType.pptx Case "rtf" Return Fso.fileType.rtf Case "tif" Return Fso.fileType.tif Case "tiff" Return Fso.fileType.tif Case "txt" Return Fso.fileType.txt Case "vb" Return Fso.fileType.vb Case "xls" Return Fso.fileType.xls Case "xlsx" Return Fso.fileType.xlsx Case "xml" Return Fso.fileType.xml Case "zip" Return Fso.fileType.zip Case Else _invalidFileType = fileType Return Fso.fileType.invalid End Select End Function 'Method supports File Upload control, returns a byteArray containing 'the file contents along with a variety of properties describing the file: ' First argument "controlID" is a pointer to the file upload control. ' Returns a ByteArray of the file contents and sets properties. Shared Function FileUploader(ByVal controlID As Object) As Byte() 'Get the uploader control into this method: Dim uploader As FileUpload = DirectCast(controlID, FileUpload) 'Get length, mimetype, and path: _fileLength = CInt(uploader.PostedFile.ContentLength) _fileMimetype = uploader.PostedFile.ContentType _filePathName = uploader.PostedFile.FileName 'Get file name and extension: Dim pattern As String = "\\(?:.+)\\(.+)\.(.+)" Dim r As Regex = New Regex(pattern) Dim m As Match = r.Match(_filePathName) _fileExtension = m.Groups(2).Captures(0).ToString() _fileName = m.Groups(1).Captures(0).ToString() 'Replace spaces and hyphens with underscores: Dim spacePattern As String = "[-\s]" Dim spaceRegex As Regex = New Regex(spacePattern) _fileName = spaceRegex.Replace(_fileName, "_") 'Remove illegal characters: Dim stripPattern As String = "[-\\/:?=<>|.+*]" Dim stripRegex As Regex = New Regex(stripPattern) _fileName = stripRegex.Replace(_fileName, "") 'Get file contents into a byte Array: Dim _fileStream As Byte() = New Byte(_fileLength) {} uploader.PostedFile.InputStream.Read(_fileStream, 0, _fileLength) uploader.PostedFile.InputStream.Close() 'Get MD5 hash of the file contents: _fileHash = Security.CreateHash(_fileStream) 'Pass the byteArray back to the caller: Return _fileStream End Function 'Method parses a filename to determine it's extension, then 'sets a flag to indicate whether it should be handled as a 'character or byte file: ' First argument "fileName" specifies the file to test ' Returns True if binary filetype, False if text filetype. Shared Function IsBinary(ByVal fileName As String) As Boolean Dim fileNameArray() As String = fileName.Split(".") Dim extension As String = LCase(fileNameArray(1)) Select Case extension Case "cs" Return False Case "csv" Return False Case ("doc") Return True Case "docx" Return True Case "gif" Return True Case "htm" Return False Case "html" Return False Case "jpg" Return True Case "js" Return False Case "mpp" Return True Case "pdf" Return True Case "png" Return True Case "pps" Return True Case "ppt" Return True Case "pptx" Return True Case "rtf" Return False Case "tif" Return True Case "tiff" Return True Case "txt" Return False Case "vb" Return False Case "xls" Return True Case "xlsx" Return True Case "xml" Return False Case "zip" Return False Case Else Return Nothing End Select End Function 'Read text stream from specified file: ' First argument "fileName" specifies the desired file to read. ' Returns a string representing the current content of the file. Shared Function ReadTextFile(ByVal fileName As String) As String Dim filePath As String = _documentBase & fileName Dim fileMode As FileMode = fileMode.Open If File.Exists(filePath) = True Then Dim fileAccessType As FileAccess = FileAccess.Read Dim fileStream As New FileStream(filePath, fileMode, fileAccessType) Dim fileReader As New StreamReader(fileStream) Try fileReader.BaseStream.Seek(0, SeekOrigin.Begin) ReadTextFile = fileReader.ReadToEnd Catch ex As Exception Throw New AppException("ERROR FSO1 -- unable to read text file: ", ex) Finally fileReader.Close() fileStream.Close() End Try Else ReadTextFile = "[ERROR: Requested file not found]" End If End Function 'Read binary stream from specified file: ' First argument "fileName" specifies the desired file to read. ' Returns a ByteArray representing the current content of the file. Shared Function ReadBinaryFile(ByVal fileName As String) As Byte() Dim filePath As String = _documentBase & fileName Dim fileMode As FileMode = fileMode.Open If File.Exists(filePath) = True Then Dim fileInput As FileStream = New FileStream(filePath, fileMode) Try Dim fileBytes(CInt(fileInput.Length - 1)) As Byte fileInput.Read(fileBytes, 0, CInt(fileInput.Length)) ReadBinaryFile = fileBytes Catch ex As Exception Throw New AppException("ERROR FSO2 -- unable to read binary file: ", ex) Finally fileInput.Close() End Try Else Return Nothing End If End Function 'Method selects the appropriate handler when it isn't known 'in advance whether the file will be character or byte: ' First argument "fileName" specifies the file to read. ' Returns an object containing either file type. ' Note: Caller will need to cast it into the correct type. Shared Function ReadFile(ByVal fileName As String) As Object If IsBinary(fileName) Then _isBinaryFile = True Return ReadBinaryFile(fileName) Else _isBinaryFile = False Return ReadTextFile(fileName) End If End Function 'Method accepts fileType as string and converts to filetype 'enumerated value, calls binary handler for output to the User Agent (typically a web browser): ' First argument "bytesIn" represents the inbound byte stream. ' Second argument "fileName" specifies the resultant filename passed to the User Agent. ' Third argument "filetype" specifies the mimetype passed to the User Agent. Public Shared Sub RenderFile(ByVal bytesIn As Byte(), ByVal fileName As String, ByVal fileType As String) RenderFile(bytesIn, fileName, ConvertFileType(fileType)) End Sub 'Method accepts fileType as string and converts to filetype enumerated 'value, calls text handler: ' First argument "textIn" represents the inbound text stream. ' Second argument "fileName" specifies the resultant filename passed to the User Agent. ' Third argument "filetype" specifies the mimetype passed to the User Agent. Public Shared Sub RenderFile(ByVal textIn As String, ByVal fileName As String, ByVal fileType As String) RenderFile(textIn, fileName, ConvertFileType(fileType)) End Sub 'Method accepts string, converts to ByteArray, then calls binary handler: ' First argument "textIn" represents the inbound text stream. ' Second argument "fileName" specifies the resultant filename passed to the User Agent. ' Third argument "filetype" specifies the mimetype passed to the User Agent. Public Shared Sub RenderFile(ByVal textIn As String, ByVal fileName As String, ByVal fileType As fileType) Dim bytesIn() As Byte = System.Text.Encoding.UTF8.GetBytes(textIn) RenderFile(bytesIn, fileName, fileType) End Sub 'Method accepts binary stream then creates payload stream to user 'agent in proper mimetype: ' First argument "bytesIn" represents the inbound byte stream. ' Second argument "fileName" specifies the resultant filename passed to the User Agent. ' Third argument "filetype" specifies the mimetype passed to the User Agent. Public Shared Sub RenderFile(ByVal bytesIn As Byte(), ByVal fileName As String, ByVal fileType As fileType) Dim fileExtension As String = String.Empty Dim mimeType As String = String.Empty Select Case fileType Case Fso.fileType.cs 'C# Source files fileExtension = "cs.txt" mimeType = "text/plain" Case Fso.fileType.csv 'Comma Separated Values format fileExtension = "csv" mimeType = "text/csv" Case Fso.fileType.doc 'MS Word 2003 and earlier fileExtension = "doc" mimeType = "application/msword" Case Fso.fileType.docx 'MS Word 2007 fileExtension = "docx" mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" Case Fso.fileType.gif 'GIF image format fileExtension = "gif" mimeType = "image/gif" Case Fso.fileType.htm 'Internet Explorer fileExtension = "htm" mimeType = "text/html" Case Fso.fileType.html 'Internet Explorer fileExtension = "htm" mimeType = "text/html" Case Fso.fileType.jpg 'JPG image format fileExtension = "jpg" mimeType = "image/jpg" Case Fso.fileType.js 'Javascript source files fileExtension = "js.txt" mimeType = "text/plain" Case Fso.fileType.mpp 'MS Project fileExtension = "mpp" mimeType = "application/vnd.ms-project" Case Fso.fileType.pdf 'PDF format fileExtension = "pdf" mimeType = "application/pdf" Case Fso.fileType.png 'PNG image format fileExtension = "png" mimeType = "image/png" Case Fso.fileType.pps 'MS Powerpoint 2003 and earlier fileExtension = "pps" mimeType = "application/vnd.ms-powerpoint" Case Fso.fileType.ppt 'MS Powerpoint 2003 and earlier fileExtension = "ppt" mimeType = "application/vnd.ms-powerpoint" Case Fso.fileType.pptx 'MS Powerpoint 2007 fileExtension = "pptx" mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation" Case Fso.fileType.tif fileExtension = "tif" 'TIF image format mimeType = "image/tif" Case Fso.fileType.rtf 'Rich Text Format fileExtension = "rtf" mimeType = "application/rtf" Case Fso.fileType.txt 'Notepad fileExtension = "txt" mimeType = "text/plain" Case Fso.fileType.vb 'VB source files fileExtension = "vb.txt" mimeType = "text/plain" Case Fso.fileType.xls 'MS Excel spreadsheet 2003 and earlier fileExtension = "xls" mimeType = "application/vnd.ms-excel" Case Fso.fileType.xlsx 'MS Excel spreadsheet 2007 fileExtension = "xlsx" mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" Case Fso.fileType.xml 'XML files fileExtension = "xml" mimeType = "application/xml" Case Fso.fileType.zip 'Zip files fileExtension = "zip" mimeType = "application/zip" Case Else fileExtension = String.Empty mimeType = String.Empty End Select If Not fileExtension = String.Empty Then HttpContext.Current.Response.ContentType = mimeType HttpContext.Current.Response.Expires = 0 HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename = " & fileName & "." & fileExtension) Dim ms As MemoryStream = New MemoryStream(bytesIn) ms.WriteTo(HttpContext.Current.Response.OutputStream) Else HttpContext.Current.Response.Write("ERROR: Your requested file "" & fileName & "." & _invalidFileType & "" is not supported for downloading.") End If HttpContext.Current.Response.End() End Sub 'Write text stream to specified file on the local disk: ' First argument "fileName" specifies the desired file to write to. ' Second argument "textIn" passes the text stream in. ' Returns True if successful, False if it fails. Shared Function WriteFile(ByVal fileName As String, ByVal textIn As String) As Boolean WriteFile = True Dim filePath As String = _documentBase & fileName Dim fileModeType As FileMode = FileMode.Create Dim fileAccessType As FileAccess = FileAccess.Write Dim fileStream As New FileStream(filePath, fileModeType, fileAccessType) Dim fileWriter As New StreamWriter(fileStream) Try fileWriter.BaseStream.Seek(0, SeekOrigin.End) fileWriter.WriteLine(textIn) fileWriter.WriteLine("") fileWriter.Flush() Catch ex As Exception Throw New AppException("ERROR FSO3 - Unable to write text file to disk: ", ex) WriteFile = False Finally fileWriter.Close() fileStream.Close() End Try End Function 'Write binary stream to specified file on the local disk: ' First argument "fileName" specifies the desired file to write to. ' Second argument "bytesIn" passes the byteArrray in. ' Returns True if successful, False if it fails. Shared Function WriteFile(ByVal fileName As String, ByVal bytesIn As Byte()) As Boolean WriteFile = True Dim filePath As String = _documentBase & fileName Dim fileMode As FileMode = fileMode.Create Dim fileStream As New FileStream(filePath, fileMode) Dim byteWriter As New BinaryWriter(fileStream) Try byteWriter.Write(bytesIn) Catch ex As Exception Throw New AppException("ERROR FSO4 -- Unable to write binary file to disk: ", ex) WriteFile = False Finally byteWriter.Close() fileStream.Close() End Try End Function 'Method writes a line to specified file (ideal for logging): ' First argument "fileName" specifies the file to write to. ' Second argment "textIn" specifies the text to write. ' Note: if file does not exist, it will be created Shared Sub WriteToFile(ByVal fileName As String, ByVal textIn As String) Dim filePath As String = _documentBase & fileName Dim fileModeType As FileMode = FileMode.Append Dim fileAccessType As FileAccess = FileAccess.Write Dim fs As New FileStream(filePath, fileModeType, fileAccessType) Dim s As New StreamWriter(fs) s.BaseStream.Seek(0, SeekOrigin.End) Try s.WriteLine(textIn) Catch ex As Exception Throw New AppException("ERROR FSO5 -- Unable to write file to disk: ", ex) Finally s.Close() End Try End Sub 'Method imports XML file into matching strongly typed instantiated object: ' Argument "objectName" specifies the object that will hold the result of the operation. ' Argument "fileName" specifies the xml file to import. Shared Sub ImportXml(ByRef objectName As Object, ByVal fileName As String) Dim sr As New StreamReader(fileName) Dim xs As New XmlSerializer(objectName.GetType) objectName = xs.Deserialize(sr) sr.Close() End Sub 'Method exports contents of strongly typed object to a xml formatted (utf-16) string: ' Argument "objectName" specifies the object to export. Shared Function ExportXml(ByRef objectName As Object) As String Dim sw As New StringWriter() Dim xs As New XmlSerializer(objectName.GetType) xs.Serialize(sw, objectName) ExportXml = sw.ToString() sw.Close() End Function 'Method exports XML file from matching strongly typed instantiated object to an xml file: ' Argument "objectName" specifies the object that holds the contents to export. ' Argument "fileName" specifies the xml file to receive the export. Shared Sub ExportXml(ByVal objectName As Object, ByVal fileName As String) Dim sw As New StreamWriter(fileName) Dim xs As New XmlSerializer(objectName.GetType) xs.Serialize(sw, objectName) sw.Close() End Sub #End Region End Class