VB.NET多线程文件读写

时间:2022-05-18 14:03:57

现在,流行的下载工具都使用了多线程的方式,这样比单线程下载快了很多。

 

不过那些通常都不是用VB.NET写的,网上可以找到的这方面的资料也比较少。自己琢磨了几天,同时也借助于网友的帮助,解决了这个问题。

 

下边上代码。

 

Imports System.IO
Imports System.Threading
Imports System.Text
Public Class Form1
Private p As String = "" '文件路径
Private fLength As Integer
Private fl As Integer = 102400 '定义缓冲区大小
Private fStart As Integer = 0 '定义读取起始位置
Private m As Integer = 1
Private fCount As Integer = 0 '分块数
Private cInte As Integer = 0 '当前块

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
p = TextBox1.Text
Dim a As New FileInfo(p)
fLength = a.Length
fStart = 0
Dim u As Thread
fStart = -fl
Dim c, d As Double
c = Int(fLength / fl)
d = fLength / fl
If c < d Then
fCount = c + 1
Else
fCount = d
End If
For i As Integer = 1 To ThreadCount.Text
u = New Thread(AddressOf Work)
u.IsBackground = True
u.Name = i
u.Start()
Next
End Sub

Sub Work()
SyncLock Thread.CurrentThread
Do While Not cInte >= fCount
fStart += fl
cInte += 1
ReadData(fStart, fl, cInte)
Loop
If cInte = fCount Then
Dim temppath As String = "E:\1\"
'========合并文件=========
Dim pm As New System.Diagnostics.Process()
pm.StartInfo.FileName = "cmd.exe"
pm.StartInfo.UseShellExecute = False
pm.StartInfo.CreateNoWindow = True
pm.StartInfo.RedirectStandardInput = True
pm.StartInfo.RedirectStandardOutput = True
pm.Start()
Dim temp As String = ""
Dim fEx As New FileInfo(p)

For i As Integer = 1 To fCount
If temp = "" Then
temp = "E:\1\" & fEx.Name.Replace(fEx.Extension, "." & i & fEx.Extension)
Else
temp = temp & " + " & "E:\1\" & fEx.Name.Replace(fEx.Extension, "." & i & fEx.Extension)
End If
Next
'MsgBox(temp)
pm.StandardInput.WriteLine("copy /b " & temp & " " & temppath & "OK.txt")
pm.StandardInput.WriteLine("exit")
pm.WaitForExit()
End If
End SyncLock
End Sub

'读取指定位置的内容
Sub ReadData(ByVal Start As Integer, ByVal l As Integer, ByVal cuinte As Integer)
Dim u As New FileStream(p, FileMode.Open, FileAccess.Read)

Dim sBy(l - 1) As Byte
u.Seek(Start, SeekOrigin.Begin)
u.Read(sBy, 0, sBy.Length)
u.Close()
u.Dispose()
writeData(cuinte, sBy)
End Sub


'写文件
Sub writeData(ByVal cuinte As Integer, ByVal data As byte())
Try
Dim fEx As New FileInfo(p)
Dim TEMP As String = "c:\" & fEx.Name.Replace(fEx.Extension, "." & cuinte & fEx.Extension)
Dim u As New FileStream(TEMP, FileMode.OpenOrCreate, FileAccess.Write)
Dim Bw As New System.IO.BinaryWriter(u)
Bw.Write(data)
u.Close()
u.Dispose()
Bw.Close()

Catch ex As Exception
Err.Clear()
Exit Sub
End Try
End Sub


Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
End
End Sub


 

在写上边代码的时候,碰到了一个文件拆分后再合并后,文件被损坏的问题,详见:http://topic.csdn.net/u/20100716/11/4addfa0d-db8e-4604-9e7b-f2e14958a59e.html

 

在此也感谢各位网友的帮助