Results 1 to 18 of 18

Thread: [RESOLVED] Delete All Files In A Folder

  1. #1

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Resolved [RESOLVED] Delete All Files In A Folder

    Code:
    Dim directoryName As String = "your path here"
    For Each deleteFile In Directory.GetFiles(directoryName ,"*.*",SearchOption.TopDirectoryOnly)
        File.Delete(deleteFile)
    Next
    This is the code that I am attempting to use to delete all the files in a single folder. However, when I run this, I receive this error: "System.ArgumentException: 'Illegal characters in path.'"

    I originally got this code https://stackoverflow.com/questions/...iles-in-folder and I saw that others had this problem. Their resolutions did not seem to help or perhaps I did not understand what they were completely saying.

    Any ideas or help would be greatly appreciated to get this simple code to work for me!!!! Thanks you guys!

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Delete All Files In A Folder

    Well, hopefully that isn't exactly what you ran. That path shown isn't a path, it's just the placeholder for the path. What did you actually put into directoryName?
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Re: Delete All Files In A Folder

    Quote Originally Posted by Shaggy Hiker View Post
    Well, hopefully that isn't exactly what you ran. That path shown isn't a path, it's just the placeholder for the path. What did you actually put into directoryName?
    Haha. No, that is not what I put. I used C:\Users\Admin\Desktop\TestFolder\

    I then added several text files to test to see if it would work

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Delete All Files In A Folder

    I followed the link you provided and I see no evidence of people having had that problem. Was it on the GetFiles call or the Delete call?

    By the way, the only reason to use Directory.GetFiles(directoryName ,"*.*",SearchOption.TopDirectoryOnly) over Directory.GetFiles(directoryName) is that you have files with no extension that you want excluded. The default behaviour is all files in the top-level folder.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Re: Delete All Files In A Folder

    Quote Originally Posted by jmcilhinney View Post
    I followed the link you provided and I see no evidence of people having had that problem. Was it on the GetFiles call or the Delete call?

    By the way, the only reason to use Directory.GetFiles(directoryName ,"*.*",SearchOption.TopDirectoryOnly) over Directory.GetFiles(directoryName) is that you have files with no extension that you want excluded. The default behaviour is all files in the top-level folder.
    I tried the same code but with a different directory "C:\Windows\Temp" and it still did not work. It sent me the same error.

    Here is a image of the throwback error.

    Name:  Capture.jpg
Views: 4194
Size:  29.5 KB


    Also, if you return back to the website that I referenced, there were comments under sujith karivelil's post in which the same error I am receiving was mentioned. sujith karivelil's post is the second post which appears on the page.

    Thanks for your time man.

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Delete All Files In A Folder

    I always find it amusing when people post stuff here that they apparently haven't looked at themselves. After upping the zoom on my browser to 200% so I could actually see what's in your screenshot, I can see that your directoryName variable begins with a line feed character. Why would you expect it to be OK to include a line feed in a folder path?

    I'm guessing that you are breaking up another String to get that path but you're doing it incorrectly. In Windows, a standard line break is comprised of a carriage return character and a line feed character. The fact that you have a String that starts with a line feed suggests that you split a larger String on carriage returns only. This is quite likely a result of having Option Strict Off and calling a method that expects a Char, resulting in the compiler implicitly converting a full line break String to just a carriage return Char. If you turn Option Strict On, as it should pretty much always be, the issue will likely be highlighted with a compilation error flagging an implicit conversion.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Re: Delete All Files In A Folder

    Quote Originally Posted by jmcilhinney View Post
    I always find it amusing when people post stuff here that they apparently haven't looked at themselves. After upping the zoom on my browser to 200% so I could actually see what's in your screenshot, I can see that your directoryName variable begins with a line feed character. Why would you expect it to be OK to include a line feed in a folder path?

    I'm guessing that you are breaking up another String to get that path but you're doing it incorrectly. In Windows, a standard line break is comprised of a carriage return character and a line feed character. The fact that you have a String that starts with a line feed suggests that you split a larger String on carriage returns only. This is quite likely a result of having Option Strict Off and calling a method that expects a Char, resulting in the compiler implicitly converting a full line break String to just a carriage return Char. If you turn Option Strict On, as it should pretty much always be, the issue will likely be highlighted with a compilation error flagging an implicit conversion.
    Right, so I did as you suggested by using Option Strict On and it indicted the error. I resolved it by changing my string a little. Here was my string after it was changed.
    Code:
    Dim TextLines() As String = UserDefinedDirectories_txt.Split(CType(Environment.NewLine, Char()))
    It works great. & I turned strict off because I prefer not to use it myself. Thank you for your help!

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [RESOLVED] Delete All Files In A Folder

    The more correct option is to use the overload of String.Split that allows you to split on a String rather than a Char. The way you're doing it, you'll end up splitting on carriage returns and line feeds separately rather than together, so a String with two lines would end up producing an array with three elements instead of two, with the middle element being the empty String between the carriage return and the line feed. Try this for yourself:
    vb.net Code:
    1. Dim text = "Line 1" & Environment.NewLine & "Line 2"
    2. Dim arr1 = text.Split(CType(Environment.NewLine, Char()))
    3. Dim arr2 = text.Split({Environment.NewLine}, StringSplitOptions.None)
    4.  
    5. For i = 0 To arr1.GetUpperBound(0)
    6.     MessageBox.Show(arr1(i), $"arr1({i})")
    7. Next
    8.  
    9. For i = 0 To arr2.GetUpperBound(0)
    10.     MessageBox.Show(arr2(i), $"arr2({i})")
    11. Next
    Last edited by jmcilhinney; May 4th, 2019 at 11:58 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [RESOLVED] Delete All Files In A Folder

    Here's an extension method that may be useful:
    vb.net Code:
    1. Imports System.Runtime.CompilerServices
    2.  
    3. Public Module StringExtensions
    4.  
    5.     <Extension>
    6.     Public Function SplitLines(source As String, Optional options As StringSplitOptions = StringSplitOptions.None) As String()
    7.         Return source.Split({ControlChars.NewLine, ControlChars.Lf}, options)
    8.     End Function
    9.  
    10. End Module
    With that module in your project (or in a library that you reference) you can then do this:
    vb.net Code:
    1. Dim textLines = UserDefinedDirectories_txt.SplitLines()
    The extension method splits on CR-LF pairs first and then splits on any remaining lone LF characters. Line feed alone is the default line break on various other platforms and the Windows implementation of RTF uses them too, e.g. WordPad or a RichTextBox control. I'm guessing that's because that is part of the RTF standard. You might want to also add lone CR characters to that as I think that that is the standard line break on certain platforms too. I think that it's LF on Unix-based platforms and CR on MacOS. OSX is Unix-based though, so I'm not sure what that means for it. Regardless, you may encounter CR-LF and LF just using files created on Windows.
    Last edited by jmcilhinney; May 4th, 2019 at 11:59 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Delete All Files In A Folder

    Quote Originally Posted by kshadow22 View Post

    It works great. & I turned strict off because I prefer not to use it myself.
    I think that everybody will eventually disagree with this statement, including yourself. I once thought that way, many years back, until I realized all the things that Option Strict off was hiding from me. Most of those work. If your code runs, it runs. If you then turn Option Strict ON and it fails to compile, then you know that the changes it is requiring are not essential. The implicit conversions you were using worked, which is most of the battle, so you don't HAVE to make them explicit conversions.

    However, when I did this for a large project that did a VERY long running calculation, I found a couple things. First off, the code performance improved by about 30-50%. It's hard to measure, precisely, as the calculation ran for several days, and I wasn't sitting around staring at the computer for that whole time. So, I noted that switching all the implicit conversions to explicit conversions shaved "about a day" off the run time of "about 3 days", but that's kind of fuzzy.

    The second thing I found was a truly subtle bug that the implicit conversions allowed. I don't remember the bug very well, except that I noted that it would work MOST of the time, though not ALL of the time, and that it was always wrong-ish.

    There is nothing you can do with Option Strict ON that you couldn't also write with Option Strict OFF, so you can write explicit conversions with Option Strict either way. Explicit conversions always perform better, though we generally won't see the difference. And, as you have found, implicit conversions can hide subtle bugs. For these reasons, you will eventually turn Option Strict ON and leave it on, so why wait?
    My usual boring signature: Nothing

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [RESOLVED] Delete All Files In A Folder

    I say that this thread is a perfect demonstration why you SHOULD prefer to turn it On. You found this issue because of an exception but what if it hadn't caused an exception? What if you had been saving this text to a database and you ended up with a database full of invalid data?

    If it seems onerous to make sure that you are using the correct data types at all times then you should give up programming now. I don't even think twice about casts and conversions now and haven't for a long time. If you have to do it then you do it and it becomes second nature. If you stick with .NET programming then there's a fair chance that you'll end up code in C# as well as VB or exclusively and it doesn't have a non-strict mode. Trust me, there's no C# developers who lament that fact.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: [RESOLVED] Delete All Files In A Folder

    Quote Originally Posted by jmcilhinney View Post
    If it seems onerous to make sure that you are using the correct data types at all times then you should give up programming now.
    Or just switch to JavaScript.
    My usual boring signature: Nothing

  13. #13
    Frenzied Member
    Join Date
    Dec 2014
    Location
    VB6 dinosaur land
    Posts
    1,190

    Re: Delete All Files In A Folder

    Quote Originally Posted by kshadow22 View Post
    I turned strict off because I prefer not to use it myself.
    OUCH. That's a terrible preference. You will learn to hate yourself for that.

  14. #14

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Re: Delete All Files In A Folder

    Quote Originally Posted by Shaggy Hiker View Post
    I think that everybody will eventually disagree with this statement, including yourself. I once thought that way, many years back, until I realized all the things that Option Strict off was hiding from me. Most of those work. If your code runs, it runs. If you then turn Option Strict ON and it fails to compile, then you know that the changes it is requiring are not essential. The implicit conversions you were using worked, which is most of the battle, so you don't HAVE to make them explicit conversions.

    However, when I did this for a large project that did a VERY long running calculation, I found a couple things. First off, the code performance improved by about 30-50%. It's hard to measure, precisely, as the calculation ran for several days, and I wasn't sitting around staring at the computer for that whole time. So, I noted that switching all the implicit conversions to explicit conversions shaved "about a day" off the run time of "about 3 days", but that's kind of fuzzy.

    The second thing I found was a truly subtle bug that the implicit conversions allowed. I don't remember the bug very well, except that I noted that it would work MOST of the time, though not ALL of the time, and that it was always wrong-ish.

    There is nothing you can do with Option Strict ON that you couldn't also write with Option Strict OFF, so you can write explicit conversions with Option Strict either way. Explicit conversions always perform better, though we generally won't see the difference. And, as you have found, implicit conversions can hide subtle bugs. For these reasons, you will eventually turn Option Strict ON and leave it on, so why wait?
    Unfortunately, I haven’t had the learning experience that most of you guys have probably had. After reading your reply, I have come to try enabling option strict. I don’t understand the entirety of it and I will have to research more about it.

    However, Just curious, where might I find more resources and information for learning more about Visual Basic & programming? My knowledge is pretty much just built from watching YouTube videos, googling, and looking at forums.
    You guys are all geniuses and it would be awesome to know how you got where you are now.

  15. #15

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Re: [RESOLVED] Delete All Files In A Folder

    Thanks for your input you guys. I read through all your replies and will turn the option strict on. You’ve all got me sold. Of course I don’t understand the entirety of it. But I am wanting to learn more. Thanks you guys

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Delete All Files In A Folder

    Quote Originally Posted by kshadow22 View Post
    Unfortunately, I haven’t had the learning experience that most of you guys have probably had. After reading your reply, I have come to try enabling option strict. I don’t understand the entirety of it and I will have to research more about it.

    However, Just curious, where might I find more resources and information for learning more about Visual Basic & programming? My knowledge is pretty much just built from watching YouTube videos, googling, and looking at forums.
    You guys are all geniuses and it would be awesome to know how you got where you are now.
    Well, aside from Google, YouTube, and forums...since none of them existed, you're following the same path that I did. I'm a fish biologist, by training, with a couple degrees in that area. I got into programming a couple different times. I was pretty casual about it back in HS and earlier, but that was the late 70s, early 80s, so most everybody was pretty casual about computers back then. After all, the best of them pretty much sucked compared to what we have these days.

    I then got into it more seriously in the mid-90s to solve some tedium with processing large amounts of fish data. At the time, I felt I needed something to occupy my mind during some routine work, so I started reading books on ASM, C, and C++. Once VB came out, I started using that. It was always a matter of solving actual problems, though. It was never academic, so I learned what I needed as I needed. After a couple decades of that....there's probably a whole lot more that I don't know than that which I know, but at least I know that I don't know what I don't know. You just never stop learning.
    My usual boring signature: Nothing

  17. #17

    Thread Starter
    Lively Member kshadow22's Avatar
    Join Date
    Dec 2014
    Location
    Kentucky
    Posts
    95

    Re: Delete All Files In A Folder

    Quote Originally Posted by Shaggy Hiker View Post
    Well, aside from Google, YouTube, and forums...since none of them existed, you're following the same path that I did. I'm a fish biologist, by training, with a couple degrees in that area. I got into programming a couple different times. I was pretty casual about it back in HS and earlier, but that was the late 70s, early 80s, so most everybody was pretty casual about computers back then. After all, the best of them pretty much sucked compared to what we have these days.

    I then got into it more seriously in the mid-90s to solve some tedium with processing large amounts of fish data. At the time, I felt I needed something to occupy my mind during some routine work, so I started reading books on ASM, C, and C++. Once VB came out, I started using that. It was always a matter of solving actual problems, though. It was never academic, so I learned what I needed as I needed. After a couple decades of that....there's probably a whole lot more that I don't know than that which I know, but at least I know that I don't know what I don't know. You just never stop learning.

    Haha. That’s awesome. Thanks for sharing that. It’s very encouraging.

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Delete All Files In A Folder

    Quote Originally Posted by kshadow22 View Post
    Unfortunately, I haven’t had the learning experience that most of you guys have probably had. After reading your reply, I have come to try enabling option strict. I don’t understand the entirety of it and I will have to research more about it.
    Having Option Strict Off effectively let's you write code while disregarding the types of variables. The compiler can either enforce strict typing, meaning that you are required to use a variable/reference of the specific type expected, or it can not. If it does, it will flag, at design time, any places where you are not using the correct type. If it does not, type checking is deferred until run time. Not enabling strict type checking in the compiler may seem like a good thing, because it means that you don't have to think too hard about the types of your objects to get your code to compile, but if you aren't thinking about the types you're using then it is much easier to use the wrong types.

    Having Option Strict On disallows two things: implicit casts/conversions and late binding. Here's an example of each that is allowed with Option Strict Off:
    vb.net Code:
    1. Dim obj1 As Object = "Hello World"
    2. Dim str1 As String = obj1 'implicit cast
    3.  
    4. Dim str2 As String = "100"
    5. Dim int2 As Integer = str2 'implicit conversion
    6.  
    7. Dim obj3 As Object = "Hello World"
    8. Dim int3 As Integer = obj3.Length 'late binding
    In the first case, the object is a String but it is initially assigned to an Object variable. That means that an Object reference is then assigned to a String variable. That is not allowed with Option Strict On because that Object reference could refer to an object that is not a String, so an exception could be thrown at run time. We can see that we're using an object of the expected type here but it may not be so obvious in more complex code.

    In the second case, a String object from a String reference is assigned to an Integer variable, which is not allowed under Option Strict On. In this case, the String does represent a valid integer so it will be implicitly converted to an Integer at run time but, if the String contained "Hello World", an exception would be thrown. Note that performing an explicit conversion doesn't guarantee that the data will be valid at run time but it having to perform an explicit conversion at least makes you think about that possibility.

    In the third case, the String.Length property is accessed via a reference of type Object. The Object type does not have a Length property so that is late-binding. Again, we can see that the actual object is a String in this simple case, but real-world code won't be so simple. With Option Strict On, you must use have a value/reference of a specific type to access members of that type. With Option Strict On, you'd have to modify that code to look something like this:
    vb.net Code:
    1. Dim obj1 As Object = "Hello World"
    2. Dim str1 As String = CStr(obj1) 'explicit cast
    3.  
    4. Dim str2 As String = "100"
    5. Dim int2 As Integer = Convert.ToInt32(str2) 'explicit conversion
    6.  
    7. Dim obj3 As Object = "Hello World"
    8. Dim int3 As Integer = CStr(obj3).Length 'early binding
    Basically, Option Strict On requires you to explicitly cast or convert such that you are always using the specific type expected by the code you are using rather than the compiler just assuming that the actual data will be the correct type. As I said, you're still not guaranteed that these casts and conversions will work but at least the potential issues are drawn to your attention and that should make you more likely to notice situations that could be problematic. Your issue here is an example of why allowing implicit conversions is bad. You used a String where a Char was expected so the compiler guessed that you wanted it to perform the implicit conversion. The problem was that you didn't want that but you didn't even know it was happening, so your code carried on executing merrily without your even being aware that it was not doing what you intended. If you had Option Strict On then the compiler would have flagged that code as an issue. That doesn't guarantee that you will then modify the code correctly but the compiler has at least let you know that a modification is required. You could still explicitly convert the String to a Char and get the wrong result but then it's on you for explicitly writing code that does something you don't want. The compiler can force you to consider potential issues but it can't ensure you solve them correctly. You still have to learn how to write the code you need.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width