• 0

[VB.NET] Delete File in process


Question

Ok gang,

I've got an interesting problem. I have a .net 2.0 app that goes off to a server to get a file and unzip it locally. This process is threaded. It's possible that during the first run through the process the end-user may need to stop the original process and go get a different file.

So, I abort the initial thread and start over. The issue? (Glad you asked) Seems that one or more files (the zip and possibly files from within the zip file, depending on how far along the initial process is) will not delete (File.Delete(path) as these files are in use my another process.

Exact error:

Description: The process cannot access the file 'c:\TestExtract\75872-01-1.ado' because it is being used by another process.

The code that is pulling the file from the zip is here:

--- BEGIN CODE CHUNK --------

If (sFileName <> String.Empty) Then

Dim StreamWriter As FileStream = File.Create(sDirectory & theEntry.Name)

Dim Size As Integer = 2048

Dim data(2048) As Byte

While (True)

Size = stmZipFile.Read(data, 0, data.Length)

If (Size > 0) Then

StreamWriter.Write(data, 0, Size)

Else

Exit While

End If

End While

StreamWriter.Close()

End If

--- END OF CODE CHUNK --------

Ive tried watching for the thread's abort request in that loop, but it never gets it. So I can't close the stream (arg)

I've looked to see if I can get the handle of the process that is using the file so I can kill the process and then the file... but so far no luck. I'm heading home now, but I'll check back in a few hours (it's 5pm est)

Thanks for any ideas.

Link to comment
https://www.neowin.net/forum/topic/578013-vbnet-delete-file-in-process/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

The quickest thing that I would offer would be to have some type of boolean variable that the code chunk continuously checks within it's while(true) loop. such as

While(_cancelZip = false)
   Size = stmZipFile.Read(data, 0, data.Length)
   If (Size &gt; 0) Then
	  StreamWriter.Write(data, 0, Size)
   Else
	  Exit While
   End If
End While

_cancelZip should be a private member variable that can be accessed externally through an Exposed Property.

After this loop, check to see if _cancelZip = true. If it is, you must close this StreamWriter and then delete the file.

Does this make sense?

  • 0

There is a FileSystemWatcher component that you may be able to use. Have you looked into that?

EDIT: Re-read your question and the FileSystemWatcher probably isn't what you're looking for.

Anyway, you are right in looking for the Abort Thread request, but the fact that you aren't getting that means that you are most likely not threading properly. Although bleepjay's solution will probably work, it is clumsy and not the way it should be done with the advent of Threading in .NET. I recommend you look at some of the many threading tutorials online.

Here are a few links I Googled quickly, hope it's useful:

http://msdn.microsoft.com/msdnmag/issues/01/07/vbnet/

http://www.devx.com/getHelpOn/10MinuteSolution/20365

http://www.stardeveloper.com/articles/disp...0404&page=1

http://blogs.msdn.com/dougturn/archive/200...and-vb-net.aspx

Edited by magik
  • 0
  bleepjay said:
The quickest thing that I would offer would be to have some type of boolean variable that the code chunk continuously checks within it's while(true) loop. such as

While(_cancelZip = false)
   Size = stmZipFile.Read(data, 0, data.Length)
   If (Size &gt; 0) Then
	  StreamWriter.Write(data, 0, Size)
   Else
	  Exit While
   End If
End While

_cancelZip should be a private member variable that can be accessed externally through an Exposed Property.

After this loop, check to see if _cancelZip = true. If it is, you must close this StreamWriter and then delete the file.

Does this make sense?

Hummm... the boolean is an intesting idea. I can set that, wait a moment and then kill the process. I'll give it a try in the morning.

magik,

As for the file system watcher... how would that help? I need to get a specific file at a specific time, not all the files (there are thousands of them!). But maybe you meant something else that I'm not getting.

  • 0

^ Yea, sorry, I didn't read your question fully the first time. I hope my edited post is of more use to you. :)

To clarify: Instead of looking for the Abort Request within your loop, you should have the loop within a Thread Process and then a separate Event Hander that Handles the Thread Abort Request. When that event is fired, it should halt the Thread Process.

Does that make more sense?

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I maintain that the Cybertruck was a social experiment.  "Can we convince the massively insecure petrol guzzling, Dodge Ram loving, right wing idiots to buy a poorly built, underpowered, underspecified, electric vehicle that they know everyone will laugh at them in"
    • Wish you could set the WiFi country without setting an SSID. This would stop the warning on every boot.
    • Huawei's Mate XT successor launches this year with a performance and camera boost by Hamid Ganji Last year, Huawei reimagined our perception of folding smartphones by launching the world's first tri-folding device, Mate XT. Contrary to regular folding smartphones like the Samsung Galaxy Z Fold 6, the Huawei Mate XT utilizes a dual-hinge mechanism that allows the device to fold into a "Z" shape. The success of the Mate XT has allegedly prompted Huawei to release a sequel this year. Chinese tipster Digital Chat Station on Weibo says Huawei will release a successor in the second half of 2025. While the folding and screen solution remain unchanged, the tipster claims the second-generation Mate XT gets a faster processor and upgraded camera setup. Digital Chat Station says Huawei will also improve the device's accessories. Last year's Mate XT included an Aramid Fiber Case with an integrated rotating stand in the box as official accessories. Though the tipster doesn't mention quality improvements, Huawei could reinforce the phone's folding endurance. As for the release date, the first-generation Mate XT was released in September 2024, and the Mate XT 2 might also be released at the same time. Interestingly, Huawei announced its Mate XT, the world's first tri-folding device, on September 10 last year, just one day after Apple announced its iPhone 16 series. If Huawei wants to tease Apple again, we can expect the Mate XT 2 to drop simultaneously with the iPhone 17 series. While these devices are not in the same category, Huawei's rivalry with Apple is common knowledge. Tri-folding smartphones provide bigger screens at a more compact size compared to tablets. For example, the Huawei Mate XT has a screen size of 10.2 inches when it's fully open and 7.9 inches when folded once. Also, when you fold it twice, you get a 6.4-inch screen like regular smartphones. Huawei is now the biggest contender in the tri-folding segment, but Samsung may also join the race with a tri-fold version of its Galaxy Fold devices.
    • You can now measure internet speed and download videos using PowerToys Run by Taras Buria PowerToys Run is among my favorite modules, which I use daily (some of them should be integrated into Windows 11). This powerful utility is great for finding stuff, launching apps, navigating the web, and a lot more. Third-party modules help expand PowerToys Run's functionality and add additional capabilities like controlling Spotify, asking ChatGPT, and more. Now, there are three new modules you may find useful: speed test, video downloader, and vocabulary. The SpeedTest module uses Ookla Speedtest CLI for local execution without third-party tracking or ads. It has a modern, theme-aware user interface, and runs with a single command: just open Run and type spt to measure your internet connection speed. The result will show up in a new window with the ability to copy the result URL. The module also supports x64 and ARM systems. The VideoDownloader plugin lets you download videos from YouTube and other websites. You can specify the video quality and format (audio-only, for example) and select where to save the video. To make it work, open PowerToys Run, type dl and add a video URL. Finally, the Definition plugin from the same developer works as a powerful vocabulary that offers word definitions, word pronunciations, phonetics and synonyms, usage examples, and more. Note that these modules are not available in PowerToys out of the box. You need to download them from GitHub and install them manually. Here is how to do that: Download SpeedTest, VideoDownloader, or Definition plugins from their GitHub repositories. Extract downloaded plugins into %LOCALAPPDATA%\Microsoft\PowerToys\PowerToys Run\Plugins\ Open PowerToys Run (Alt + Space is the default shortcut) and launch plugins using their corresponding shortcuts (spt, dl, or def, all three can be customized in settings). You can also configure plugins in PowerToys Run settings. You can find more third-party modules for PowerToys Run on GitHub.
    • Showing people how to self host their own media is harmful, according to YouTube by David Uzondu YouTube has taken down a video from tech creator Jeff Geerling that demonstrated how to use LibreELEC, a lightweight operating system for turning devices into media centers, on a Raspberry Pi 5 for 4K video playback. The video, titled "I replaced my Apple TV—with a Raspberry Pi", originally published in May 2024, was removed in June 2025 under YouTube's "Harmful or dangerous content" policy. According to the violation notice, YouTube claimed the video showed "how to get unauthorized or free access to audio or audiovisual content, software, subscription services, or games that usually require payment." Image via Jeff Geerling Geerling strongly refuted YouTube's claims. He stated clearly, "I purposefully avoid demonstrating any of the tools that are popularly used to circumvent purchasing movie, TV, and other media content." He also emphasized that his own Network Attached Storage, or NAS, contains only legally acquired content. This isn't Geerling's first run-in with YouTube over self-hosted media tools. Last October, his tutorial titled "Better than Disney+: Jellyfin on my NAS" was hit with a similar strike for showing how to set up Jellyfin, an open source media server for organizing and streaming personal media. That strike was quickly overturned after an appeal. But this time, YouTube rejected his appeal, even though the LibreELEC video had been live for over a year, had racked up over half a million views, and contained no promotion of anything illegal. This whole thing feels a lot like what happened with youtube-dl. It's a simple command-line tool for downloading videos, used by tons of people for perfectly legal reasons like saving public domain content or backing up their own uploads. But that didn't stop the RIAA from hitting it with a DMCA takedown on GitHub, calling it a piracy tool. The community pushed back hard, and eventually it was brought back, thanks in part to support from groups like the Electronic Frontier Foundation who pointed out that not everything that can be misused is automatically bad. Side note, the youtube-dl project appears to be unmaintained (the last release was in 2021), if you're looking for an alternative, consider its very popular fork, yt-dlp. After the appeal was rejected, YouTube required Geerling to complete "policy training" to avoid a more serious, permanent strike on his channel. He eventually gave in and took the training. Anyways, if you're interested, he has uploaded the removed LibreELEC video to Internet Archive for anyone to watch.
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      439
    2. 2
      +FloatingFatMan
      247
    3. 3
      snowy owl
      226
    4. 4
      ATLien_0
      212
    5. 5
      Xenon
      152
  • Tell a friend

    Love Neowin? Tell a friend!