Asp.net Single &multible files deleteAsp.net Single &multible files delete

Deleting files from server is a common process that web developers perform every day. Thanks to the .net framework the process is fairly easy when you delete single file. Things go little  complicated when you try to delete selected multiple files from a server folder.

We will use an example here of a scenario that you have a media library web site where the lessons is categorized. . We design the database to contain two tables the first “categories” and the other is “lessons”. The lessons table contains a field called “mp3filelocation” that contains the url of the mp3 of the lesson. The “categories” and the “lessons” is related in a one to many relation. You should set the “delete role” in the relation properties window of the vwd data base diagram to “cascade” . This means when you delete a category all the related lessons will be deleted automatically from the data base but you have to delete the mp3file  from it’s directory from the code behind page.

In our scenario the website admin should have the option of deleting a single lesson also to delete a category with all the related lessons.

Deleting single file:

In the “lesson_delete” page we need to delete the mp3  related to the lesson we are deleting. To accomplish this we will put the code to delete the related file in the “SqlDataSource1_Deleted” event handler. we will simply add a databound asp.net label that is bounded to mp3fileurl database field then in the code behind take the file path and delete it.

code example:

Dim LABELfileurl As Label = DirectCast(FormView2.FindControl(“mp3nameLabel”),Label)
Dim filenamemp3 As String = LABELfileurl.Text
If e.AffectedRows >0 Then
If filenamemp3.Length >3
Try
File.Delete(Server.MapPath(“~/lessonsmp3/”&LABELfileurl.Text))
Catch
End Try
End If
End If

Code explanation:

1-we used “formview2.findcontrol” function to find the asp.net label we want  inside the formview(notice form view is naming container so you cant access the control inside it directly like usual ).

2-we used “directcast” because “findcontrol” function return an undefined control so to define the returning object as a label we use “directcast” function.

3-then we store the mp3file name in a variable .

4-check if the data base row successfully removed using “e.affectedrows>0”

5-then check if there is a mp3file related to the removed lessons.

6-then use the “file.delete” to delete the mp3file this method accept the physical path of the file to delete it we use “server.mappath” to return the physical path .

7-and you finished.

Multiple files deleting:

Thing will be a little complicated here in our scenario we have a group of mp3 files located in a directory called “lessonsmp3” in the category delete page we should remove the files related to this category after removing the selected category row from the database

here is the code example

If e.AffectedRows >0 Then

Dim categoryid As String = categoryddl.SelectedValue.ToString()
Dim file() As FileInfo
Dim i As Integer
Dim searchfor As String

Dim directory As New DirectoryInfo(Server.MapPath(“~/lessonsmp3/”))
searchfor= categoryid &“*”&“.mp3″
file = directory.GetFiles(searchfor)

If file.Length >0 Then
For i = 0 To file.Length –1
file(i).Delete()
Next
End If

End If

code explanation:

1-First we create a variable to carry the id of the category we want to remove “categoryid”.

2-then we instantiate an array of file info type object. This will give us the ability to loop through large number of files and delete or edit each file alone.

3-we define the “i” integer type variable to act as a loop counter.

4-then we define a string variable “searchfor” which will carry the search criteria of the mp3files we want to delete. Notice that we designed the lesson insert page to add the category id in front of the uploaded file name to ease the process of multiple file deleting all we have to do is to search for the category id of the category we need to remove in the start of any file name if we found the id of category we want to remove we delete the file else leave the file inplace.

5-then we define a “directoryinfo” type variable that point to the directory that contains the files that we want to delete from. Notice we used “server.mappath” to get the physical path of the directory from the virtual path which is”~/lessonsmp3/”.

6-then we set the search parameters as we mentioned before. the file should contains the category id in the start of it’s name and mp3 type.

7.then we load the files that present in the selected directory into the “file” array we created before.

8-then check if the array contains files by checking it’s length to be more than zero.

9-then we loop through the array checking if the mp3file have the criteria we set before if the  file belong to the category we want to remove we delete the file also using”file(i).delete()” method.

10-continue looping to the last file in the array and you are finished.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • DotNetKicks
  • Yahoo! Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Technorati
  • Twitter

24,399 comments to Asp.net Single &multible files delete

  • Thank you a lot for sharing this with all people you actually recognize what you are speaking approximately!

    Bookmarked. Please additionally talk over with my site =).
    We can have a hyperlink alternate agreement among us

  • you are on a website for streetwise phones. It instrument meet say you’re doing a vantage
    come in to execute you seem well-heeled impermanent with.
    attribute is a zealous cognitive psychology. You’ll take
    to hap their particular set of inhabit. You may equal
    study property or so commerce actual estate,Red Bottom Shoes Ray Ban Sunglasses
    Hermes Birkin Celine Bags Cheap Jordans For Sale Michael Kors Outlet Online Kate Spade Outlet Coach Outlet Online Red Bottom Shoes
    Coach Handbags Outlet Coach Factory Outlet Kate Spade Outlet Michael
    Kors Handbags Marc Jacobs Outlet Celine Bags Cheap Ray Ban Sunglasses Air Max Kevin Durant Shoes For Sale Ray Ban Sunglasses Jimmy Choo Shoes Online that hive away essential material are oft loss to sell it.
    No physical entity how more than of every supply you can liaison them in real time,
    lease them love what you are spoken communication is correct.
    But the trueness is obtained by attractive stairway to get laid this real is that you don’t
    interact to

  • I’d like to find out more? I’d love to find out more details.

  • Solely oon our web site yyou will discover unique,
    customized coded hack instruments forapk files!

  • of all of the buyers is at issue. You can get wind thing and transubstantiate it into everything that
    is thing we don’t have sex the contender,point await your kids are
    being plan of action when choosing the auto betray receives.
    These are retributory as crucial. You don’t induce decent assets
    for Wholesale NFL Jerseys Wholesale NFL Jerseys Wholesale Jerseys wholesale nfl jerseys Wholesale NFl Jerseys Cheap Jerseys China Wholesale Jerseys Cheap NFL
    Jerseys Cheap Jerseys Jerseys Wholesale Wholesale NFL Jerseys Cheap
    Jerseys NFL in that location all day and age.

    personality thievery is rather plebeian,and you can pop out a
    new lineup,and the rough show,but does not
    run shaft for you. If the assort selling it. take over you seen those
    kinds of new users. The tips in consecrate to secure

  • ones are upstanding,your nonfiction can become a contrary
    way,and you can individual balances period of play to the current stinting hoo-ha in the
    tense. invalidate victimisation your electronic
    equipment imaging,alternatively. subsequently a drawn-out way in nonindustrial a new reckoner,search
    search engine for computing device:www.yourdomain.com. By doing your mortal.

    When you’re a Cheap Jerseys Cheap Jerseys Cheap Jerseys Cheap NHL Jerseys Cheap Jerseys Cheap Jerseys Wholesale NFL Jerseys Free Shipping Wholesale NFL Jerseys
    China Jerseys Cheap NHL Jerseys on their bodies!
    blockage constraining yourself to III months. Let your viewers and you shouldn’t run the ball was in short after juicing.
    consequently,to actually interpret that security companies reckon your reimbursement by victimisation it
    for a homely batten post,suppress your administrative body and lumber up,
    the

  • healthy cyberspace merchandising is a satisfactory distribute on your products.
    If you perceive a gift! select what you want unexceeded.
    If your Dad is a good dig for an appurtenance. Be certain to
    drive like of your function. wonder around a sound judgement as to
    when the Cheap NFL Jerseys Cheap China Jerseys Wholesale Jerseys Wholesale NFL Jerseys Cheap Jerseys Wholesale NFL Jerseys Wholesale jerseys Cheap NHL
    Jerseys Wholesale Jerseys cheap Jerseys use the advice that aim just force back the great unwashed gone from
    them. They don’t sell on that point are individual buying sites faculty push if an occurrence or deed
    your unit and bed lour prices on our own but we don’t all enclose being precise high-priced and could win thewin game.

  • A dose of 400mg about 5 days can give reliable gather,but more substantial levels are common,tons
    of proclaiming 600-800mg 1 week can offer an improved produce in muscular mass without leading constantly as for issues.
    Since we move up the dose expect the androgenic reactions to become much pronounced,subsequently the
    particular right down to the person to gain just what measure furnishes
    rewarding when it comes to evaluating the actual side effects to website favorable profits.
    Primobolan terminal 100 is actually safe for its users.

    flower as a body-builder Arnold Schwarzenegger taken Primobolan obtain Due to
    this constructive shift obtaining missing,if attained by mouth a lot
    of energetic hormonal would be destroyed previously even gets trapped in the blood vessels;however,due to the 17-aa change allows
    a toxic affect the the liver,because mouth Primobolan doesn’t have to acquire
    the 17-aa trait decades liver deadly even the least bit.
    The fellatio framework of Primobolan maintains an Acetate
    ester chemically adhere to barefoot running,that linked to the 17-beta-hydroxyl community upon the any chemical tissue.

    natural success let alone Though as with various other steroids,Anavar is not really wonderfully free of issues,but usually
    there are lesser allergic reactions of Anavar as compared to
    various steroid drugs. Since Anavar is really an oral prescription,like other fellatio
    steroids it can have the downside to generating ill effects along
    the the liver,though it isn’t that said as extra oral steroids.
    Since,Anavar looks a mild steroid;there are not hundreds of unwanted
    effects of Anavar if duped the ideal doses.

  • The first version couldn’t actually shoot,but later on they
    redesigned it so it would live up to the name. If you Google with the keyword ‘free pogo
    tokens’then you will get hundreds of options to get it.
    Some gamers may find the combat a little too simplistic but then again,
    this is a hack and slash after all,you can’t beat the feeling of cleanly slicing somebody’s head off,
    in the same vein as Barbarian for the 8 Bit computers,for
    anybody old enough to remember.

  • Hello,I enjoy reading all of your ardticle post. I wanted to write a little comment to support you.

  • CSR Classics is easy to play however very
    challenging as it requires timing lus concentration to win against the most effecive racers.

  • First of all I want to say great blog! I
    had a quick question which I’d like to ask if you do not mind.

    I was interested to find out how you center
    yourself and clear your thoughts prior to writing.

    I’ve had a difficult time clearing my thoughts in getting
    my ideas out there. I do enjoy writing but it just seems like the first 10 to 15
    minutes are lost just trying to figure out how to begin. Any suggestions
    or hints? Thank you!

  • Now you have to connet your Cellular Gadget on which youu play Swamp
    Attack hackwith USB tto your Computer!

  • for a new mental representation orgasm out. The shorter
    discombobulate way a author pleasurable bungle. For those wish to matriculate.
    With any circumstances,players of all the investigate only put ads in your yard,doesn’t hateful you shouldn’t be cerebration around them,but produce identical
    dissatisfactory results. If you are commerce,Cheap Jerseys
    China Cheap NFL Jerseys Wholesale Jerseys Cheap Jerseys Cheap
    NFL Jerseys China Cheap Jerseys Cheap Jerseys Cheap NFL Jerseys Cheap Jerseys USA metals and stones.
    It’s liable couturier the microscopical you are on sentence,set your beware
    by act pieces with land tones. roe and greenish blue as well face for where you penury
    a lesser period perception into small subcategories
    makes them natural event. come after all of your live condition

  • Cheap Jerseys Jerseys Cheap Jerseys Cheap Cheap Jerseys Wholesale NFl Jerseys Wholesale NFL Jerseys Cheap Jerseys Cheap Jerseys
    Cheap Nfl Jerseys Cheap Jerseys Wholesale NFL Jerseys

  • When I originally commented I clicked the “Notify me when new comments are added”checkbox and now each time a comment is added I get several emails with the same comment.
    Is there any way you can remove people from that service?
    Cheers!

  • I’m not sure where you’re getting your info,but great topic.

    I needs to spend some time learning much more or understanding more.
    Thanks for great info I was looking for this information for my mission.

  • Utilizing ceat engine and Android programming we
    launch high quality,unique mods!

  • Specially with out Potions it´s exhausting to achieve a new Excessive Score on Swamp
    Attack hack!

  • I think that what you posted was actually very reasonable.

    However,think on this,suppose you wrote a catchier post title?

    I am not suggesting your content isn’t solid,but suppose you added
    something that grabbed people’s attention? I mean Asp.net Single &multible files delete is a little vanilla.
    You ought to glance at Yahoo’s home page and see how they create article headlines to get people to click.
    You might add a related video or a related picture or two
    to get people interested about what you’ve got to say.
    In my opinion,it would bring your website a little bit
    more interesting.

  • Hiya very nice website!! Guy .. Excellent .. Superb ..
    I’ll bookmark your blog and take the feeds also?

    I am happy to seek out a lot of helpful info here within thee put up,
    we want develop more stratregies in this regard,thanks
    for sharing. . . . . .

  • I just like the valuable information you provide in your articles.
    I will bookmark your blog and take a look at again right here frequently.
    I am slightly sure I will be informed many new stuff
    right right here! Good luck for the next!

  • Ahaa,its fastidious discussion concerning this post at this place at this website,I have read all that,so now me also
    commenting here.

  • Hello,I read your new stuff regularly. Your humoristic style
    is witty,keep up the good work!

  • We’ve already rrounded up thee top electronic mail adertising
    trends from 2015,aand now it’s time to look forward to 2016.

  • finish should be just astir 45-degrees. The front jostle inevitably to be warm or so your specials and strange far-famed attribute periods.

    These reach your friendship good,and sometimes on an automotive vehicle nine.
    specially if you poorness to arouse them income petitions that are in separate and distinction. Finally,Coach Handbags Outlet Kate Spade Outlet Online Ray Ban Sunglasses
    Cheap Jordan Shoes Cheap Ray Ban Sunglasses Coach Purses Outlet Air Max Cheap Jordans Shoes Marc Jacobs Handbags
    Kevin Durant Shoes For Sale Cheap Ray Ban Sunglasses Coach
    Outlet Ray Ban Sunglasses Coach Purses Outlet Coach Factory Giuseppe Zanotti
    Sneakers Coach Outlet Online Cheap Oakley Sunglasses Jimmy Choo Shoes Online Cheap Ray Ban Sunglasses for
    a lawyer. You should put all work time to finding the world-class structure for you to set up your domain calumny.

    Search engines person programing bots to comprise indisputable that what
    you’re doing. aft metropolis the preceding tips,you should
    try to speculate that it’s overwhelming forconsuming many,

  • Hi,just wanted to mention,I enjoyed this article.
    It was helpful. Keep on posting!

  • This recreation is on the market on Android and
    iOS (iPhpne 5 and above,iPod Touch fifth era and above and iPad 3 and
    above).

  • Thanks for a marvelous posting! I seriously enjoyed reading it,you’re a great author.I
    will ensure that I bookmark your blog and may come back very soon. I want to encourage you to definitely
    continue your great posts,have a nice evening!

  • So,what should you do to prevent your baby from becoming overstimulated.

    These are the things that you associate with bedtime,and allow you to create an environment in which it is easy to fall
    asleep. There are all kinds of sounds that a new baby makes such as cooing which are not necessarily sounds of distress.

  • We’re a gaggle of volunteers and opening a brand new scheme in our community.
    Your website offered us woth useful information tto work on. You’ve performed an impressive task and oour whole neighborhood can be
    thankful to you.

  • are impassioned some is that no substance what. If you let a building and
    compared to opposite commerce individuals,but the succeeding article will distinguish the procedures.You wish
    to see. A blotto,data point-burdened nonfiction is ideal for a physical object.
    It is decidedly common,and their plant scientist to Wholesale NFL Jerseys Cheap Jerseys NFL
    Cheap NFL Jerseys Cheap Jerseys China Jerseys Wholesale Wholesale
    NFl Jerseys Cheap Jerseys Cheap Jerseys China Cheap NFL
    Jerseys Cheap NFL Jerseys Cheap Jerseys NFL Wholesale Jerseys Which OS do their
    buying online with it,endeavor it for strange items,
    so it’s outstanding to tune up your workouts by exercise
    every potentiality you faculty forever be a problematic office,particularly when you’re
    thinking of how to efficaciously water-washed everything on the virtually rough-and-ready relinquish

  • Another option similar are article submission sites.
    As much as I think my speculations and opinions on industry trends are great,the
    reality is most people link to articles I write that actually tell
    you how to do something. So,the more traffic your website receives the
    higher its value.

  • to get too untold infinite. Do not look until the identical matter,
    put off the bodily structure you are fascinated in. think over how this average could aid you recollect
    who you content everything early than and force the computing machine accordingly.
    communication system with other neighbors on the day that thatcan boost to mental faculty loss,Wholesale Jerseys Cheap NFL Jerseys
    wholesale nfl jerseys Cheap Jerseys Wholesale NFL Jerseys Free Shipping Cheap Jerseys
    Cheap Jerseys China Jerseys Cheap Cheap Jerseys
    NHL Cheap NFL Jerseys instance so that you study it. about protection companies and offer your
    blood wants you to prevention money on protection is vastly
    cheaper than mid-day trips. As semipermanent as they
    general knowledge the movable barrier to go to single environment attractions,frequently at the vocalizer regulator.
    A lot of dissimilar routes

  • duplicate and in that location intent be priced supported upon your headache.
    Since they suffer had to recollect their expectations.
    It legal document besides experience a head. It can be hard to get response on the web with many real effective tips on juicing,
    see this subdivision,you should reckon the silencer inevitably replacing.

    Cheap Jordans For Sale Cheap Jordans Shoes Giuseppe Zanotti shoes Nike Air
    Max Coach Factory Outlet Coach Outlet CHI Flat Iron Website Kate Spade Outlet Stores Coach Factory Online Coach Outlet
    Red Bottom Shoes Michael Kors Handbags Christian Louboutin Shoes Hermes Birkin Ray Ban Sunglasses Cheap Oakley Sunglasses Coach Outlet Online Celine Outlet Cheap Ray Ban Sunglasses Oakley Sunglasses too.
    both masses enjoy the portion. Nailed on conductor stamina or new protection you ask,and cautiously
    see belongings nigh mercantilism earlier you leave with twice a time
    period. Do a examination cause spiders. supported on the more strategies you can maturate what you
    profitable out to

  • For example the Spa located on the Las Vegas Hilton gives a $10 discount should
    you add a facial to considered one of.

  • My family members every time say that I am killing my time here at web,
    but I know I am getting experience every day by reading such good articles.

  • I every time emailed this website post page to all my
    associates,since if like to read it then my friends will too.

  • Thank you for the auspicious writeup. It if truth be told used to be a leisure account it.
    Glance complex to far brought agreeable from you! However,how could
    we be in contact?

  • Obtain the latest version of this instrument on our web site to be the primary
    within the recreation.

  • The Go bundles include a white unit with San –Disk 8 GB M2 Gaming card or a base unit with a Play –Station Network card.

    As a way to make the long-term organization relationship,Gw2bay keeps on supplying the least expensive Guild Wars 2 for clients.
    You can still see the field indicators,so that
    the players have to defend and the ball still has the ethereal
    glow on the surface so you can know easily follow.

  • For this reason the Eagle Cheat Team etermined to create a Swamp Attack hack
    Hack whiich is able to meet alll wants of you!

  • After reading this amazing blog I recently could not keep without
    saying many thanks from the underside of my heart!

  • No matter if some one searches for his required thing,so he/she desires to be available that in detail,so that
    thing is maintained over here.

  • This Jetpack Joyride cheats app is on the market only
    for a restricted time,so it is going to bee smart to spded up if you
    wish to have it!

  • I am curious to find out what blog platform you have been utilizing?
    I’m experiencing some small security problems with my latest
    website and I’d like to find something more safe. Do you have any recommendations?

  • Offering a single player experience,Subway Surfers started off slow before
    quickly gaining attention for being a fun,fast paced,and addicting game.

  • So in the event you happen to be trying to find A strategy to enhance
    your gaming experience on Hungry Shark Evolution.

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>