Jump to content
Sign in to follow this  
NeoLogy

[vb.net]macam Mana Nak Check Filesize Lebih Daripada Set Maxfilesize

Recommended Posts

Salam,

Aku nak create satu function yang akan check size file. Aku tak perlukan size file yang sebenar kerana function ni cuma perlu check adakah file tersebut lebih besar daripada size yang ditetapkan atau tidak. Ideanya begini; function ni akan read file ni by chunck of data. Let say file tu bersize 1GB. Kalau gunakan GetFileSize(), sudah tentu mengambil masa yang lama untuk dapatkan size file tersebut. Ini akan merugikan masa kerana aku hanya perlu tahu adakah file tersebut bersize lebih daripda 10MB?

Kalau file lebih daripada 10MB, function akan return true dan return false kalau kurang daripada 10MB. Dengan membaca file by chunck, let say 1024byte on each chunck, kalau total read chunck size lebih daripada 10MB, then automatically return true tanpa perlu baca chunck seterusnya.

So, nak tanya macam mana nak read file by chunck?
Kalau ada contoh, lagi bagus. Atau kalau ada mana-mana references ke..

Share this post


Link to post
Share on other sites

Selalunya cara saya, akan gunakan FileInfo...

 

Jadi bila saya check size file tersebut.. saya akan buat seperti ini..

 

 private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog f = new OpenFileDialog();
            
            
            if (DialogResult.OK == f.ShowDialog())
            {
                string a = f.FileName;

                FileInfo sizeBytes = new FileInfo(a);
                                
                if (sizeBytes.Length > 10485760)
                {
                    MessageBox.Show("Your size file is " + sizeBytes.Length.ToString() + " is bigger");
                    return;
                }
                else
                {
                    //Your logic

                }
            }
        }

 

 


10485760 bytes sama la 10MB.. Jadi apabila kita gunakan sizeFile.Length, kita boleh dapatkan size dia dalam bentuk bytes.. Jadi hanya perlu buat If statement, sekiranya lebih kita return semula.. kalau rendah kita buat proses kita sendiri...

 

Happy Programming...;)

Share this post


Link to post
Share on other sites
Operasi FileInfo() ni same ke dgn FileSize()?

In term of speed? Mane lebih laju n less resource pkai..utk file less than 100MB, rasanya xde beza sgt..bagaimana kalau file tu 1GB atau 3GB? Sbb exact size info xperlu..utk dpt actual size, of course dia akan count every bytes..dan itu semestinya akan amik masa dan resource..why not count byte smpai 10MB je..kalau lebih trus skip count byte dan return true..

Any idea nk read by chunck?

Share this post


Link to post
Share on other sites
Rasanya aku dah dapat idea yang lebih baik..Tak perlu count byte..Cuma read byte ke 10485760, kalau return some value, then return true..kalau EndOfStreamException triggered, bermakna file tersebut tak smpai pun size 10MB..
Public Function isFileSizeBig(ByVal filename As String,ByVal Size as Integer) As Boolean
   Try
      Dim fs = New IO.FileStream(filename,IO.FileMode.Read + IO.FileMode.Share)
      Dim fr = New IO.BinaryReader(fs)

      fr.BaseStream.Position = Size

      If Not fr.ReadByte() = Nothing Then 
         fs.Dispose
         Return True
      End If
   
   Catch ex As EndOfStreamException

      Return False

   End Try   

End Function
Edited by NeoLogy

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Similar Content

    • By wisel
      Mencari Vb Developer Utk Handwriting Recognition System Using Svm

      harga kalau boleh dibincang kan utk yg berminat

      tolong email sy di [email protected]
    • By orance
      saya tak tahu macam mana nak buat coding untuk validation password. dia ada 1 button sahaja iaitu button sign in pada interface. hanya 2 user sahaja yang dibenarkan sign in dan interface akan memaparkan gambar user yang log in....

      This program only allows two users to sign-in which means, we have to set the username and password in the program itself.
      User1
      Username: Felix
      Password: sand
      User 2
      Username: Hendry
      3
      Password: flower
      4. Use If…else if statements to verify which user is signing in.
      5. When the user clicks the button Sign In, it will prompt user to enter the first name.
      (Set in your program the username is “Felix”).
      6. After entering the first name, it will prompt again asking for password.
      (Set in your program the password is “sand”).
      If the user entered the correct values for first name and password, it will display the message box greeting the user’s name as follow
      "hello felix!Ready to play
    • By merahPutih
      [color=#0000cd]Hi,
      Nak mintak pendapat korang sket~~

      Source code ni aku dapat dari programmer lame (ni file DLL).
      Dia gune dll ni kat app dier dan stakat ni aku tengok cam ok.
      ni sourcecode tu[/color]

      [code]Private Sub SendToPort(ByVal code As String)
      Dim logstr2 As String = ""
      Dim ByteSend(16) As Byte
      Dim str As String
      Dim strArray() As String = code.Split("#")
      Dim k As Integer
      Dim l As Integer
      Dim dataSize As Integer
      Try
      logstr2 = "1"
      gCount = UBound(strArray) + 1
      logstr2 = "2"
      dataSize = gCount + 5
      logstr2 = "3"
      ByteSend(0) = 2
      logstr2 = "4"
      ByteSend(1) = 3
      logstr2 = "5"
      ByteSend(2) = dataSize
      logstr2 = "6"
      ByteSend(3) = strArray(0)
      logstr2 = "7"
      If gCount > 1 Then
      l = 0
      For k = 4 To (UBound(strArray) + 3)
      l = l + 1
      ByteSend(k) = strArray(l)
      Next k
      End If

      logstr2 = "8"
      str = CheckSum("#B#C#" & dataSize & "#" & code)
      logstr2 = "9"
      ByteSend(gCount) = Asc(Mid(str, 1, 1))
      logstr2 = "10"
      ByteSend(gCount + 1) = Asc(Mid(str, 2, 1))
      logstr2 = "11"
      Log_Rtn("gCount = " & gCount.ToString & vbNewLine & "logstr2 = " & logstr2)
      cv.Write(ByteSend, 0, gCount + 2)
      logstr2 = "12"
      Dim bolWait As Boolean
      bolWait = Wait_Fnc()
      logstr2 = "13"
      tmpRev1 = ByteSend(gCount + 1)
      logstr2 = "14"
      Catch ex As Exception
      Log_Rtn("clsB2B|SendToPort|" & ex.Message & logstr2 & "," & gCount & "," & code)

      End Try
      End Sub[/code]


      [color=#0000cd]jadi masalah aku ialah bile aku GO(F5), Result yang aku dapat salah, bile aku letak breakpoint lpastu step into (F10), baru dapat result yang aku nak[/color]

      [color=#0000cd]Breakpoint tu aku letak kat sini[/color]

      [CODE]
      bolWait = Wait_Fnc()
      [/CODE]

      [color=#0000cd]ni Wait_Fnc()[/color]

      [color=#333333][CODE]
      Private Function Wait_Fnc() As Boolean
      intWaitLoop = 0
      tmrWait.Enabled = True
      Do While tmrWait.Enabled = False
      'Do Nothing[/color]
      [color=#333333]Return False
      End Function
      [/CODE][/color]


      [color=#0000ff]aku pakai visual studio 2008

      ape yang ak dapat dari google, dorg suruh pastikan semua variable dah initialize , build mode = debug[/color]
      [color=#0000ff]then aku try- still prob yang same
      kalau build mode = release pun same jugak[/color]
      [color=#0000ff]sekarang ni aku pakai [/color][color=#0000FF]build mode = debug[/color]

      [color=#0000FF]ade gak yang swh pakai [/color][color=#0000FF]application.doevents, yang ni aku x dapat try (maybe pasal ni class??? )[/color]

      [color=#0000ff]so aku nak mintak pendapat korang,
      rase2 nye kenape ak dapat result macam ni?? ade lagi mane2 setting yang aku perlu buat ke??[/color]
    • By mon678
      Tiada Error tp x kuar data kt text field huhu harap ada org blh membantu
      sy gune visual studio 2008 dan sql server 2005..
      sy membuat sistem gune windows form





      [CODE]Private Sub Cari_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cari.Click
      Dim searchby As String = ""
      If ComboBox1.SelectedIndex = -1 Then
      MessageBox.Show("Please select search by field.", "Error")
      ElseIf (txtCari.Text.Trim() = "") Then
      MessageBox.Show("Please enter StafID number or IC number.", "Error")
      ElseIf ComboBox1.SelectedIndex = 0 Then
      searchby = "StafID"
      Else
      searchby = "kp"
      Dim con As SqlConnection = New SqlConnection("server =localhost;database=Library;Integrated Security=True;Trusted_Connection = yes")
      Dim myInsertQuery As String = "SELECT * FROM Staf WHERE " + searchby + " = '" + txtCari.Text + "'"
      Dim myCommand As New SqlCommand(myInsertQuery, con)
      Dim Dr As SqlDataReader
      con.Open()
      Dr = myCommand.ExecuteReader()
      While (Dr.Read())
      txtStaffID.Text = Dr("StafID").ToString()
      txtNama.Text = Dr("nama").ToString()
      txtKP.Text = Dr("kp").ToString()
      'txtDob.Text = Dr("dob").ToString()
      txtAddress.Text = Dr("alamat").ToString()
      txtBandar.Text = Dr("bandar").ToString()
      txtNegeri.Text = Dr("negeri").ToString()
      txtposkod.Text = Dr("poskod").ToString()
      txtNegara.Text = Dr("negara").ToString()
      txtEmail.Text = Dr("email").ToString()
      txthp.Text = Dr("hp").ToString()
      djawatan.SelectedItem = Dr("jawatan").ToString()

      End While

      UbahSuai.Enabled = True
      UbahSuai.Text = "Edit"
      con.Close()
      con.Dispose()
      End If
      End Sub[/CODE]
    • By mie_kkm
      [img]http://i.imgur.com/OpDy2.jpg[/img]
      salam semua...klu bila siap install vb.net pastu bila nak buka projek yg telah kita buat terkeluar benda ni.... projek yg kita buat tu xleh nak buka... napa eh? mintak tolong dari semua yg pakar..... dulu buat projek ni dlm pc (window XP) yg dah sedia ada vb.net... skrg istall kat pc (window 7) tapi xleh nak buka la......
      TOLONG ya
×
×
  • Create New...