''' -----------------------------------------------------------------------------
''' Project : SHYC.PublicMethods
''' Class : PublicMethods.FileOperateMethods
'''
''' -----------------------------------------------------------------------------
''' <summary>
''' 文件的相关操作方法
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [陈立功] 2006-3-25 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Class FileOperateMethods
''' -----------------------------------------------------------------------------
''' <summary>
''' 读取指定文件数据到Byte数组中
''' </summary>
''' <param name="fileName">指定文件名</param>
''' <returns>Byte数组</returns>
''' <remarks>
''' <para>不对文件的正确性进行判断,调用者自行捕获错误</para>
''' </remarks>
''' <history>
''' [] 2006-3-25 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function GetFileDataToByte(ByVal fileName As String) As Byte()
Dim fs As System.IO.FileStream
Dim w As System.IO.BinaryWriter
Dim fr As System.IO.BinaryReader
Dim iLen As Long
Try
fs = New System.IO.FileStream(fileName, System.IO.FileMode.Open)
w = New System.IO.BinaryWriter(fs)
iLen = fs.Length()
Dim b(iLen) As Byte
fr = New System.IO.BinaryReader(fs)
b = fr.ReadBytes(iLen)
w.Close()
fr.Close()
Return b
Catch ex As Exception
ErrorOperate.Writelog(fileName & ":" & ex.Message)
If Not IsNothing(w) Then w.Close()
If Not IsNothing(fs) Then fs.Close()
Throw ex
End Try
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' 将二进制数据写入到指定文件中
''' </summary>
''' <param name="fileName">指定文件名</param>
''' <param name="fileData">二进制数据</param>
''' <remarks>
''' </remarks>
''' <history>
''' [] 2006-3-25 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub WriteByteToFile(ByVal fileName As String, ByVal fileData() As Byte)
Dim tempFileName As String
tempFileName = fileName.Trim & ".temp"
Dim fs As System.IO.FileStream
Dim w As System.IO.BinaryWriter
Try
'若文件已存在,先备份文件
If System.IO.File.Exists(fileName) Then
If System.IO.File.Exists(tempFileName) Then
System.IO.File.Delete(tempFileName)
End If
System.IO.File.Copy(fileName, tempFileName)
System.IO.File.Delete(fileName)
End If
fs = New System.IO.FileStream(fileName, System.IO.FileMode.CreateNew)
w = New System.IO.BinaryWriter(fs)
w.Write(fileData)
w.Close()
fs.Close()
'删除备份文件
If System.IO.File.Exists(tempFileName) Then System.IO.File.Delete(tempFileName)
Catch ex As Exception
ErrorOperate.Writelog(fileName & ":" & ex.Message)
If Not IsNothing(w) Then w.Close()
If Not IsNothing(fs) Then fs.Close()
'有错误时从备份文件恢复原始文件
If System.IO.File.Exists(tempFileName) Then
System.IO.File.Copy(tempFileName, fileName)
System.IO.File.Delete(tempFileName)
End If
Throw ex
End Try
End Sub
End Class