Shkarko Skedarin llogaritjen e shpejtësisë dhe progresin-Sfondi Worker & Progress bar

13 shkurt 2009 nga AcidRaZor · Lini nje Koment
Paraqitur sipas: . NET , Programim 101

Këtu është një kod që do të përdorë VB.NET e klasës Backgroundworker dhe të iniciojë një kërkesë web për ta shkarkuar një skedar. Ajo do të llogaritur shpejtësinë e file-së, si dhe tregojnë se mbi përparimin e një shtylle progresi. Të gjitha duke i mbajtur Forma kryesore në dispozicion.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 
 'Where the program save the file Delegate Sub ChangeTextsSafe ( ByVal length As Long , ByVal position As Integer , ByVal percent As Integer , ByVal speed As Double ) Delegate Sub DownloadCompleteSafe ( ByVal cancelled As Boolean ) Public Sub DownloadComplete ( ByVal cancelled As Boolean ) Me . txtFileName . Enabled = True Me . btnDownload . Enabled = True Me . btnCancel . Enabled = False If cancelled Then Me . Label4 . Text = "Cancelled" 'MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information) Else Me . Label4 . Text = "Successfully downloaded" 'MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Me . ProgressBar1 . Value = 0 Me . Label5 . Text = "Downloading: " Me . Label6 . Text = "Save to: " Me . Label3 . Text = "File size: " Me . Label2 . Text = "Download speed: " Me . Label4 . Text = "" End Sub Public Sub ChangeTexts ( ByVal length As Long , ByVal position As Integer , ByVal percent As Integer , ByVal speed As Double ) Me . Label3 . Text = "File size: " & Math. Round ( ( length / 1024 ) , 2 ) & " KB" Me . Label5 . Text = "Downloading: " & Me . txtFileName . Text Me . Label4 . Text = "Downloaded " & Math. Round ( ( position / 1024 ) , 2 ) & " KB of " & Math. Round ( ( length / 1024 ) , 2 ) & "KB (" & Me . ProgressBar1 . Value & "%)" If speed = - 1 Then Me . Label2 . Text = "Download speed: calculating..." Else Me . Label2 . Text = "Download speed: " & Math. Round ( ( speed / 1024 ) , 2 ) & " KB/s" End If Me . ProgressBar1 . Value = percent End Sub Private Sub btnDownload_Click ( ByVal sender As System. Object , ByVal e As System. EventArgs ) Handles btnDownload. Click If Me . txtFileName . Text <> "" AndAlso Me . txtFileName . Text . StartsWith ( "http://" ) Then Me . SaveFileDialog1 . FileName = Me . txtFileName . Text . Split ( "/" c ) ( Me . txtFileName . Text . Split ( "/" c ) . Length - 1 ) If Me . SaveFileDialog1 . ShowDialog = Windows. Forms . DialogResult . OK Then Me . whereToSave = Me . SaveFileDialog1 . FileName Me . SaveFileDialog1 . FileName = "" Me . Label6 . Text = "Save to: " & Me . whereToSave Me . txtFileName . Enabled = False Me . btnDownload . Enabled = False Me . btnCancel . Enabled = True Me . BackgroundWorker1 . RunWorkerAsync ( ) 'Start download End If Else MessageBox. Show ( "Please insert valid URL for download" , "Warning" , MessageBoxButtons. OK , MessageBoxIcon. Warning ) End If End Sub Private Sub btnCancel_Click ( ByVal sender As System. Object , ByVal e As System. EventArgs ) Handles btnCancel. Click Me . BackgroundWorker1 . CancelAsync ( ) 'Send cancel request Try Me . bckZip . CancelAsync ( ) Catch ex As Exception 'Do Nothing End Try End Sub Private Sub BackgroundWorker1_DoWork ( ByVal sender As System. Object , ByVal e As System. ComponentModel . DoWorkEventArgs ) Handles BackgroundWorker1. DoWork 'Creating the request and getting the response Dim theResponse As HttpWebResponse Dim theRequest As HttpWebRequest Try 'Checks if the file exist theRequest = WebRequest. Create ( Me . txtFileName . Text ) theResponse = theRequest. GetResponse theRequest. Timeout = 10000000 Catch ex As Exception MessageBox. Show ( "An error occurred while downloading file. Possibe causes:" & ControlChars. CrLf & _ "1) File doesn't exist" & ControlChars. CrLf & _ "2) Remote server error" , "Error" , MessageBoxButtons. OK , MessageBoxIcon. Error ) Dim cancelDelegate As New DownloadCompleteSafe ( AddressOf DownloadComplete ) Me . Invoke ( cancelDelegate, True ) Exit Sub End Try Dim length As Long = theResponse. ContentLength 'Size of the response (in bytes) Dim safedelegate As New ChangeTextsSafe ( AddressOf ChangeTexts ) Me . Invoke ( safedelegate, length, 0 , 0 , 0 ) 'Invoke the TreadsafeDelegate Dim writeStream As New IO. FileStream ( Me . whereToSave , IO. FileMode . Create ) 'Replacement for Stream.Position (webResponse stream doesn't support seek) Dim nRead As Integer 'To calculate the download speed Dim speedtimer As New Stopwatch Dim currentspeed As Double = - 1 Dim readings As Integer = 0 Do If BackgroundWorker1. CancellationPending Then 'If user abort download Exit Do End If speedtimer. Start ( ) Dim readBytes ( 4096 ) As Byte Dim bytesread As Integer = theResponse. GetResponseStream . Read ( readBytes, 0 , 4096 ) nRead += bytesread Dim percent As Integer = ( nRead / length ) * 100 Me . Invoke ( safedelegate, length, nRead, percent, currentspeed ) If bytesread = 0 Then Exit Do writeStream. Write ( readBytes, 0 , bytesread ) speedtimer. Stop ( ) readings += 1 If readings > = 5 Then 'For increase precision, the speed it's calculated only every five cicles currentspeed = 20480 / ( speedtimer. ElapsedMilliseconds / 1000 ) speedtimer. Reset ( ) readings = 0 End If Loop 'Close the streams theResponse. GetResponseStream . Close ( ) writeStream. Close ( ) If Me . BackgroundWorker1 . CancellationPending Then IO. File . Delete ( Me . whereToSave ) Dim cancelDelegate As New DownloadCompleteSafe ( AddressOf DownloadComplete ) Me . Invoke ( cancelDelegate, True ) Exit Sub End If Dim completeDelegate As New DownloadCompleteSafe ( AddressOf DownloadComplete ) Me . Invoke ( completeDelegate, False ) End Sub whereToSave Dim Si String 'Ku e programit të ruajtur kartelën Delegat Nen ChangeTextsSafe (gjatësia ByVal Si Long ByVal pozicion, Si Integer ByVal për qind, Si Integer, ByVal shpejtësi Si dopio) Delegat Nën DownloadCompleteSafe (ByVal anuluar Si Boolean) Nën Publik DownloadComplete (ByVal anuluar Si Boolean) Mua. txtFileName. Enabled = True Mua. btnDownload. Enabled = True Mua. btnCancel. Enabled = False Nëse anulohen pas meje. Label4. Tekst = "anulluar" 'MessageBox.Show ("i ndërprerë" Shkarko, "i ndërprerë", , MessageBoxIcon.Information) tjetër Mua. Label4 MessageBoxButtons.OK. Tekst = "shkarkuar me sukses" 'MessageBox.Show ("shkarkuar me sukses!", "Të gjithë OK", MessageBoxButtons.OK, MessageBoxIcon.Information) Fundi Nëse Mua. ProgressBar1. Vlera = 0 Mua. Label5. Tekst = "Shkarkim:" Mua. Label6. Tekst = "Ruaj për të:" Mua. Label3. Tekst = "Madhësia e dokumentit:" Mua. Label2. Tekst = "shpejtësinë Shkarko:" Mua. Label4. Tekst "" End Sub Public Sub ChangeTexts (ByVal Si gjatësi Long, ByVal pozicion Si Integer, ByVal qind Si Integer, ByVal Si shpejtësi Double) Mua. Label3 =. Tekst = "Madhësia e dokumentit:" & Math. Round ((gjatësi / 1024) , 2) & "KB" Mua. Label5. Tekst = "Shkarkim:" & Mua. txtFileName. Tekst Mua. Label4. Tekst = "Shkarkuar" & Math. Round ((pozitë / 1024), 2) & "KB të" & Math. Round ((gjatësi / 1024), 2) & "KB (" & Me. ProgressBar1. Vlera & "%)" Nëse shpejtësia = 1 - Pastaj Mua. Label2. Tekst = "shpejtësia Shkarko: llogaritjen ..." tjetër Mua. Label2. Tekst = "shpejtësinë Shkarko:" & Math. Round ((shpejtësia / 1024), 2) & "KB / s" End Nëse Mua. ProgressBar1. qind Fundi = Vlera Nën privat btnDownload_Click Nën (dërgues ByVal Si Sistemit . Object, ByVal e si sistem. EventArgs) trajton btnDownload. Kliko Nëse Mua. txtFileName. Tekst <> "" AndAlso Mua. txtFileName. Tekst. StartsWith ("http://") Pastaj Mua. SaveFileDialog1. Emri i skedarit Mua. txtFileName . Tekst. Split ("/" c) (Mua. txtFileName. Tekst. Split ("/" c). Length - 1) Nëse Mua. SaveFileDialog1. ShowDialog = Windows. Formave. DialogResult. rregull pra Mua. whereToSave = Mua. SaveFileDialog1. filename Mua. SaveFileDialog1. filename = "" Mua. Label6. Tekst = "Ruaj për të:" & Me. whereToSave Mua. txtFileName. Enabled = False Mua. btnDownload. Enabled = False Mua. btnCancel. Enabled = True Mua. BackgroundWorker1 . RunWorkerAsync () 'shkarko Fundi Start Nëse të tjerët MessageBox. Show ("Ju lutem shkruani URL të vlefshme për" shkarko, "Kujdes", MessageBoxButtons. rregull, MessageBoxIcon. Paralajmërimit) Fundi Nëse End Sub Private Sub btnCancel_Click (dërgues ByVal Si Sistemit. Object, Si ByVal e Sistemit. EventArgs) trajton btnCancel. Kliko Mua. BackgroundWorker1. CancelAsync () 'Dërgo anuloni kërkesën Provo Mua. bckZip. CancelAsync () kap ish Si Përjashtim' u japin fund Asgjë Provo End Sub Private Sub BackgroundWorker1_DoWork (dërgues ByVal Si Sistemit. Object, ByVal e sistemit Si. ComponentModel. DoWorkEventArgs) trajton BackgroundWorker1. DoWork 'Krijimi i kërkesës dhe marrjen e Dim theResponse përgjigje Si HttpWebResponse theRequest Dim Sa HttpWebRequest Mundohuni' verifikimin nëse ekziston skedari theRequest = WebRequest. Krijo (Mua. txtFileName. Tekst) = theResponse theRequest. theRequest GetResponse. Timeout = 10000000 kap ish Si Përjashtim MessageBox. Show ("Ndodhi një gabim gjatë shkarkimit të file. Possibe shkakton:" & ControlChars. CrLf & _ "1) File nuk ekziston" & ControlChars. CrLf & _ "2) Remote server error", "Gabim", MessageBoxButtons. rregull, MessageBoxIcon. Error) cancelDelegate Dim Sa reja DownloadCompleteSafe (AddressOf DownloadComplete) Mua. adhurojnë (cancelDelegate, True) Exit Sub End Provo gjatësi Dim Sa Long = theResponse. ContentLength 'Madhësia e përgjigjes (në bytes) safedelegate Dim Si ChangeTextsSafe (AddressOf ChangeTexts) Mua. adhurojnë (safedelegate, gjatësi, 0, 0, 0) "thërrasim TreadsafeDelegate Si writeStream Dim re io. FileStream (Mua. whereToSave të reja, io. . Krijo) "Ndërrimi FileMode për Stream.Position (lumë webResponse nuk mbështetje të kërkuar) Dim nRead Si integruese 'Për të llogaritur shkarko shpejtësi speedtimer Dim Sa reja kronometër Dim currentspeed Si Double = - 1 lexime Dim Sa Integer = 0 A Nëse BackgroundWorker1 . CancellationPending Pastaj "Nëse ndërpritet përdorues shkarko Dil japin fund Nëse speedtimer. Start () Dim readBytes (4096) Siç Dim Byte bytesread Si Integer = theResponse. GetResponseStream. Lexoni (readBytes, 0, 4096) + nRead = bytesread qind Dim Sa Integer = (/ nRead gjatësi) * 100 Mua. adhurojnë (safedelegate, gjatësi, nRead, për qind, currentspeed) Nëse bytesread = 0 Pastaj Dil A writeStream. Shkruaj (readBytes, 0, bytesread) speedtimer. Stop () lexime + = 1 Në qoftë se leximet> = 5 Pastaj "Për rritjen precize, shpejtësia është llogaritur vetëm çdo pesë cicles currentspeed = 20480 / (speedtimer. ElapsedMilliseconds / 1000 speedtimer). Reset () = 0 lexime Fundi Nëse 'Mbyll loop streams theResponse. GetResponseStream. Mbylle () writeStream . Mbylle () Nëse Mua. BackgroundWorker1. CancellationPending Pastaj io. File. Fshije (Mua. whereToSave) Dim cancelDelegate Si reja DownloadCompleteSafe (AddressOf DownloadComplete) Mua. adhurojnë (cancelDelegate, True) Exit Sub End Nëse completeDelegate Dim Sa reja DownloadCompleteSafe (AddressOf DownloadComplete ) Mua. adhurojnë (completeDelegate, False) End Sub 

SEO Powered by Platinum SEO nga Techblissonline