2010-01-29 30 views
0

我用这个函数将文件转换为字节数组:共享文件的字节数组

Public Function ConvertToBytes(ByVal path As String) As Byte() 
     Dim _tempByte() As Byte = Nothing 
     If String.IsNullOrEmpty(path) = True Then 
      Throw New ArgumentNullException("File not exist", path) 
      Return Nothing 
     End If 
     Try 
      Dim _fileInfo As New IO.FileInfo(path) 
      Dim _NumBytes As Long = _fileInfo.Length 
      Dim _FStream As New IO.FileStream(path, IO.FileMode.Open, IO.FileAccess.Read) 
      Dim _BinaryReader As New IO.BinaryReader(_FStream) 
      _tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes)) 
      _fileInfo = Nothing 
      _NumBytes = 0 
      _FStream.Close() 
      _FStream.Dispose() 
      _BinaryReader.Close() 
      Return _tempByte 
     Catch ex As Exception 
      Return Nothing 
     End Try 
    End Function 

它的所有工作都权当是不共享的文件,但是当文件被共享的,我去的这行代码例外:

Dim _FStream As New IO.FileStream(path, IO.FileMode.Open, IO.FileAccess.Read) 

我的功能有什么问题?

谢谢!

+0

你得到什么异常?你可以发布它吗? – Oded 2010-01-29 10:46:29

+0

我的代码捕获异常我去异常和函数Return Nothing。 – Comii 2010-01-29 10:52:50

+0

肯定会与@ danbystrom的第二个答案,但是当你调试它可以评论出try/catch,所以你可以看到异常。或者至少在某处记录异常的结果。 – 2010-01-29 14:38:35

回答

0

你还没有说应该允许共享FileStream。有应该是一个separeate超载:

FileStream(String, FileMode, FileAccess, FileShare) 

而是利用这个内置的方法是不是很简单:

IO.File.ReadAllBytes(String)