Friday, 27 April 2012

ASP.net Copy using File Stream

This below code snippet will be so useful for copying the file from one physical location to another physical location in a server.  ASP.net has inbuilt classes IO.Filestream that is so useful for various file manipulation function.
Code
Public Shared Sub CopyFiles(ByVal srcPath_File As String,ByVal dstPath_File As String)

        Dim oFile As System.IO.FileInfo

        Dim oFileStream As System.IO.FileStream = Nothing
        Dim oFileStreamR As System.IO.FileStream = Nothing
        Try
            oFile = New System.IO.FileInfo(srcPath_File)
            oFileStream = oFile.OpenRead()

            Dim lBytes As Long = oFileStream.Length
            Dim fileData(lBytes) As Byte
            oFileStream.Read(fileData, 0, lBytes)

            If File.Exists(dstPath_File) ThenFile.Delete(dstPath_File)
            oFileStreamR = New System.IO.FileStream(dstPath_File, System.IO.FileMode.OpenOrCreate)
            oFileStreamR.Write(fileData, 0, fileData.Length)
            oFileStreamR.Flush()
            oFileStreamR.Close()
            oFileStreamR.Dispose()
        Catch ex As Exception
            Throw ex
        Finally
            oFileStream.Close()
            oFile = Nothing
            If oFileStreamR IsNot Nothing Then
                oFileStreamR = Nothing
            End If
        End Try
End Sub
Explanation of the code as below,
  1. Use System.IO namespace
  2. Create an instance for the fileinfo class to get the file information of the source file.
  3. Create two instances of filestream one for reading and other for writing the file.
  4. Find the length of the filestream object and store in a byte variable.
  5. Check to see the file already exist in the destination location. If file already exist in the location then delete the file.
  6. Using the filestream read instance read the content of the file and write the content in the target location using the filestream write instance.
  7. Flush and close the filestream write instance.
  8. Finally close the filestream instances.

No comments:

Post a Comment