VB.NET TCP / IP图像发送&接收

时间:2017-05-24 03:38:23

标签: .net vb.net image tcp ip

你好我在下面的一些VB.NET代码有问题,当我在客户端截取屏幕截图我将其保存为图像并将其发送到服务器,当服务器收到图像时,它将其保存到文件夹和我的picturebox1打开我收到的保存图像并显示它,它在第一次发送时工作正常,但在第二次发送时我得到一个错误,如下所示:

  

该进程无法访问该文件   ' C:\用户\根\桌面\ RECEIVED_FILES \ 01.png'因为它正在被使用   通过另一个过程。

服务器/接收代码:

Dim Listener As TcpListener = CType(Result.AsyncState, TcpListener)
Dim Client As TcpClient = Listener.EndAcceptTcpClient(Result)
Dim Name As String
Dim Path As String
Dim Data As Long
Dim Binary As New IO.BinaryReader(Client.GetStream)

Name = Binary.ReadString
Data = Binary.ReadInt64
Path = IO.Path.Combine("C:\Users\" & Environment.UserName & "\Desktop\RECEIVED_FILES\", Name)

Dim Buffer(8092) As Byte
Dim ReadTotal As Long = 0
Dim Reading As Integer = -1

'-----------> below is were the error indicated (something with stream) ---------

Using Stream As New IO.FileStream(Path, IO.FileMode.Create, IO.FileAccess.Write)
    Do Until ReadTotal = Data
        Reading = Client.GetStream.Read(Buffer, 0, Buffer.Length)
        Stream.Write(Buffer, 0, Reading)
        ReadTotal += Reading
    Loop
End Using

Binary.Close()
Client.Close()

PictureBox1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\Desktop\RECEIVED_FILES\01.png")

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

Image.FromFile方法锁定文件,直到放置Image对象。如果你已完成Image个对象,那么你应该调用它的Dispose方法,这样你就可以先解锁文件并允许它被覆盖。

If PictureBox1.Image IsNot Nothing Then
    PictureBox1.Image.Dispose()
End If

或者,在VB 2017中:

PictureBox1.Image?.Dispose()

您还可以设置ImageLocation的{​​{1}}属性,而不是调用PictureBox,然后您就不会首先锁定该文件。但是,当你完成它时,你仍然应该处理Image.FromFile

Image

顺便说一下,如果您想获取当前用户的桌面文件夹,那么您应该使用PictureBox1.ImageLocation = "C:\Users\" & Environment.UserName & "\Desktop\RECEIVED_FILES\01.png") My.Computer.FileSystem.SpecialDirectories.Desktop

Environment.GetFolderPath(Environment.SpecialFolder.Desktop)