?
Solved

Need to take the contents of a selected folder in a DirListBox and save it to a file I specify in my Output file text box

Posted on 2007-07-26
62
Medium Priority
?
388 Views
Last Modified: 2012-05-05
                                                                 Visual Basic 2005

I have a DriveListBox and a DirListBox. They are working together right now to let the user select a drive and a folder. I also have a textbox below that displays the output file. The output file is going to consist of the contents inside the folders I select from the drive and Dirlistbox. I have a start button that when clicked will start the whole process. When clicked it should take the contents in side the selected folder from the Drivelistbox & Dirlistbox and put it in to the file I specify in my output file textbox.  I would think that the code to make this happen should all be done inside my StartButton_click routine. I just don't have a clue what code would make this happen. Any sugestions would be wonderfull. Like I have said in my past 2 questions I posted on here yesterday I am totally new to VB and you have to break it down pretty simple for me.
0
Comment
Question by:vvandevender
  • 33
  • 17
  • 9
  • +1
62 Comments
 
LVL 48

Expert Comment

by:jpaulino
ID: 19577239
I don't understand right. Can you be more cear in what you want ?
0
 
LVL 48

Expert Comment

by:jpaulino
ID: 19577322
Do you want to put in a file (*.txt) the names of the file or another thing?
0
 
LVL 2

Expert Comment

by:drekow
ID: 19577506
Sounds like to me that he wants a txt file that contains the names of the files in the selected folder. Please give more information vvandevender.

Dale
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19577587
Something like...

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim outputFile As String = TextBox1.Text
            Dim sw As New System.IO.StreamWriter(outputFile)
            Dim folder As String = DirListBox1.DirList(DirListBox1.DirListIndex)
            For Each file As String In My.Computer.FileSystem.GetFiles(folder)
                sw.WriteLine(file)
            Next
            sw.Close()
            Process.Start(outputFile)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub
0
 
LVL 2

Expert Comment

by:drekow
ID: 19577686
Thats what I was thinking Idle Mind. I wanted to make sure that was what he was after. Thanks and I hope that will help him.

Dale
0
 
LVL 48

Expert Comment

by:jpaulino
ID: 19577718
Yes the problem with lots some post! Not clear information to help  :-)
0
 

Author Comment

by:vvandevender
ID: 19577755
Yes, a txt file is exactly what I need to be created. I will show you the code I have right now generating data into the textbox. The textbox is just the path of where I want the contents of the folder to go. However, I think all of the action is going to take place inside my start button routine.

Yes, I want to put the contents of the folder inside a txt. file.

I have several check boxes that user can click on that determine what contents of the folder will be added to the output (*.txt) file.
 
The first option the user has is to include files. If the user checks this, then the file names inside the folder will be saved to the output text file.  The user also has the option to click a Full Paths check box and when the user clicks this the app will include the full path along with file names. The user also has a check box that includes extensions. So if the user checks this box the output file will include the filename plus the extension.

There is one more check box associated with the files and its called Full Information. When the user selects this box the full file information is displayed in the output file.

The other check box gives the user the option of adding the full path of the folder name at the top of the Txt. File. The folder name is always included in the output file. If the user selects the Full Paths in Folder Titles check box it includes the Full path name, if the user does not select it, the just the folder name is used.

 









Some of the folders the user clicks on will have sub folders inside them. The user has a check box called Include sub folders and by clicking this the application will include the subfolders in the outfile file.

The folder name is always the first thing displayed in the output file.
0
 

Author Comment

by:vvandevender
ID: 19577758
Here is an example of the output file when all check boxes are checked.

C:\My Downloads
===============

C:\My Downloads\2006zdcrreport.txt            10097       12/01/2006     2:58:17 PM
C:\My Downloads\2007zdcrreport.txt            10097       12/01/2006     2:58:17 PM
C:\My Downloads\vbsetup.exe                   2961088     02/08/2007     2:01:25 PM
C:\My Downloads\RealPlayer10-5GOLD_bb.exe     12977680    11/15/2006     1:55:45 PM
0
 
LVL 2

Expert Comment

by:drekow
ID: 19577866
Idle Mind's code will work for you. You will have to make some adjustments to the code. You can either write the text file first and then open it into the textbox or write to the textbox then save the file.

save the file to HDD:
Dim sw As New System.IO.StreamWriter(Full Destination Path and file name)

Depending on the boxes checked would determine how much work goes in this loop.

            For Each file As String In My.Computer.FileSystem.GetFiles(folder)
                sw.WriteLine(file)
            Next

Honestly at the moment I can'r remember if 'file' returns the full path or not but I am pretty sure it does and I am sure Idle Mind can clear that up if I am wrong. If the user only wants the filename then you will have to manipulate the 'file' string before writing it.

If there is an easier way let us know but I usually use the split command and take the value of the last element in the array to get the file name alone.

dim a as string()  = split(file,"\")
sw.WriteLine(a(a.getupperbound(0))

I hope this helps and if anyone else wants to add to this please do. I am only going off memory right now.

Dale


0
 

Author Comment

by:vvandevender
ID: 19577877
That works, but the catch is that is displaying the full paths. I also want to include the actual folder name at the top of the text file. And I want the check boxes mentioned above to interact with the output file accordingly. That part is giving me fits. I wish I could paste form design on here but it is not letting me that would help alot.
0
 
LVL 2

Expert Comment

by:drekow
ID: 19578234
Taking Idle Mind's code from above it would look something like this:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim outputFile As String = TextBox1.Text
            Dim sw As New System.IO.StreamWriter(outputFile)
            Dim folder As String = DirListBox1.DirList(DirListBox1.DirListIndex)
            sw.WriteLine(folder) 'Writes the folder name
            For Each file As String In My.Computer.FileSystem.GetFiles(folder)
                If Checkbox1.Checked then 'assumes full Information
                    'Code for full information here
                ElseIf Checkbox2.Checked then 'assumes Include files. I am assuming just the filename without the path
                    Dim a as string() = split(file,"\")
                    sw.Writeline(a(a.getupperbound(0)))
                ElseIf Checkbox2.Checked then 'assumes full path
                    sw.WriteLine(file)
                End If
            Next
            sw.Close()
            Process.Start(outputFile)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

Having your code would be helpful also. I hope this helps you out.

Dale
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19578345
Taking the kids to the Pool...

I'll post another way to do it when I get back k?

(that is if no one else posts an acceptable solution before I get back...)
0
 

Author Comment

by:vvandevender
ID: 19578360
Will this code work if all the checkboxes are checked? That is a option too.. The user can check more than one check box..
0
 

Author Comment

by:vvandevender
ID: 19578370
Also would it be pretty easy to add sort logic to that loop. I need to sort the output file by the folder contents Names, Sizes, Extensions, or date. This selection is done by a Radio button and only one of the four can be selected at one time.
0
 
LVL 2

Expert Comment

by:drekow
ID: 19578408
I am putting this into a program and will get you the results.
0
 

Author Comment

by:vvandevender
ID: 19582105
Thank you guys so much for you help. I know the question keeps growing and growing. This is a tremendous learning experience for me, and you guys have really really helped me learn alot from my previous questions. I just keep running into things I have never had to do before and I search around for a few hours (google) and try things and they are getting me no where. Trust me, I am not just throwing questions out, I am trying for myself to get it done for a few hours before I come here asking for help.
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 19582468
Play with this...

It is the "core" of what you are trying to do.  I'll let you tie it all together with a pretty GUI though.

Public Class Form1

    Private Enum SortBy
        Name
        Extension
        Size
        LastWrite
    End Enum

    Private Sub DriveListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DriveListBox1.SelectedIndexChanged
        DirListBox1.Path = DriveListBox1.Drive
    End Sub

    Private files As List(Of System.IO.FileInfo)
    Private mySortOrder As SortBy = SortBy.Name
    Private IncludeSubdirectories As Boolean = True

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim folder As String = DirListBox1.DirList(DirListBox1.DirListIndex)
            files = New List(Of System.IO.FileInfo)
            Dim di As New System.IO.DirectoryInfo(folder)
            GetFiles(di, files, IncludeSubdirectories)

            Select Case mySortOrder
                Case SortBy.Name
                    files.Sort(AddressOf Me.SortByName)

                Case SortBy.Extension
                    files.Sort(AddressOf Me.SortByExtension)

                Case SortBy.Size
                    files.Sort(AddressOf Me.SortBySize)

                Case SortBy.LastWrite
                    files.Sort(AddressOf Me.SortByLastWrite)

            End Select

            Dim outputFile As String = TextBox1.Text
            Dim sw As New System.IO.StreamWriter(outputFile)
            For Each fi As System.IO.FileInfo In files
                sw.WriteLine(fi.Name & "," & fi.Length & "," & fi.LastWriteTime & "," & fi.FullName)
            Next
            sw.Close()
            Process.Start(outputFile)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub GetFiles(ByVal di As System.IO.DirectoryInfo, ByVal fileList As List(Of System.IO.FileInfo), ByVal IncludeSubdirectories As Boolean)
        fileList.AddRange(di.GetFiles())
        If IncludeSubdirectories Then
            For Each subDi As System.IO.DirectoryInfo In di.GetDirectories
                GetFiles(subDi, fileList, IncludeSubdirectories)
            Next
        End If
    End Sub

    Private Function SortByName(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiA.Name.CompareTo(fiB.Name)
    End Function

    Private Function SortByExtension(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        If fiA.Extension <> fiB.Extension Then
            Return fiA.Extension.CompareTo(fiB.Extension)
        Else
            Return fiA.Name.CompareTo(fiB.Name)
        End If
    End Function

    Private Function SortBySize(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiA.Length.CompareTo(fiB.Length)
    End Function

    Private Function SortByLastWrite(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiA.LastWriteTime.CompareTo(fiB.LastWriteTime)
    End Function

End Class
0
 
LVL 2

Expert Comment

by:drekow
ID: 19585116
I hope this works. I have not been able to post comments. Looks like Idle Mind got some code for you. Thanks Idle Mind. Let us know if this works out for you.

Dale
0
 

Author Comment

by:vvandevender
ID: 19594510
I understand the sort code part, but I am not sure if the checkbox code above will work for my app. The checkbox code above looks as if it will work with only one checkbox being checked at a time. The user has the option to select as many check boxes they want. There are 7 checkboxes on the form that all do different functions but they all have to have the ablity to be selected with any other check box or boxes and work. Then after I get that working I will try and tie the sort logic in with that. Now the sort logic is correct because the user can only select one radio button at a time. I just have to figure out how to make all the sorts and checkboxes give me the final result I want.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19594620
The code I posted just outputs everything:

            Dim outputFile As String = TextBox1.Text
            Dim sw As New System.IO.StreamWriter(outputFile)
            For Each fi As System.IO.FileInfo In files
                sw.WriteLine(fi.Name & "," & fi.Length & "," & fi.LastWriteTime & "," & fi.FullName)
            Next
            sw.Close()

So what you could do instead is build up a "line" based on which CheckBoxes are selected:

    Dim output As String
   
        output = ""
        If something Then
            output = fi.Name
        End If
        If somethingElse Then
            output = output & "," & fi.Length
        End If
        etc...

        sw.WriteLine(output)
0
 
LVL 2

Expert Comment

by:drekow
ID: 19595247
In the example I did but did not get to post due to internet issues I gave each checkbox a value and used a variable to keep up with the value.

checkbox1 = 1, checkbox2 = 2, checkbox3 = 4, etc... and when the check changes then you either add or subtract the given value from the variable holding the value. I then used a select case to determine what boxes were selected.

select case value
case 0 ' none of the checkboxes are checked. Use default output
case 1 ' checkbox1 is only checked
case 2 ' checkbox2 is only checked
case 3 ' checkbox1 and checkbox2 are checked
case 4 ' checkbox 3 is only checked
.
.
.
end select

based on the value you will know what kind of string to return to the writer to be writen.
I hope this helps

Dale
0
 
LVL 2

Expert Comment

by:drekow
ID: 19595276
Here is what I mean about the checkbox values changing

Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

If CheckBox1.Checked Then

value += 1

Else

value -= 1

End If

End Sub

Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox2.CheckedChanged

If CheckBox2.Checked Then

value += 2

Else

value -= 2

End If

End Sub

Private Sub CheckBox3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox3.CheckedChanged

If CheckBox3.Checked Then

value += 4

Else

value -= 4

End If

End Sub

Here is my select case statement. I was using system.io.fileinfo to get the information. I also wrote the results out to a textbox for this example.

Select Case value

Case Is <= 0 'no checkboxes are checked

TextBox1.Text &= f.FullName.PadRight(100) & f.CreationTime.ToShortDateString.PadRight(17) & f.Length.ToString & " Bytes" & vbNewLine

Case 1 'full information

TextBox1.Text &= f.Name.PadRight(50) & f.CreationTime.ToShortDateString.PadRight(17) & f.Length.ToString & " Bytes" & vbNewLine

Case 2 'include files

TextBox1.Text &= f.Name.PadRight(50) & vbNewLine '& f.CreationTime.ToShortDateString.PadRight(17) & f.Length.ToString & "KB" & vbNewLine

Case 3 'full information + include files

TextBox1.Text &= f.Name.PadRight(50) & f.CreationTime.ToShortDateString.PadRight(17) & f.Length.ToString & " Bytes" & vbNewLine

Case 4 'full path

TextBox1.Text &= f.FullName & vbNewLine

Case 5 'full path + full information

TextBox1.Text &= f.FullName.PadRight(100) & f.CreationTime.ToShortDateString.PadRight(17) & f.Length.ToString & " Bytes" & vbNewLine

Case 6 'full path + include files

TextBox1.Text &= f.FullName.PadRight(100) & f.Name & vbNewLine

Case 7 'full path + include files + full information

TextBox1.Text &= f.FullName.PadRight(100) & f.Name.PadRight(50) & f.CreationTime.ToShortDateString.PadRight(17) & f.Length.ToString & " Bytes" & vbNewLine

End Select

0
 

Author Comment

by:vvandevender
ID: 19601009
Dale,

Your select case portion of this code I assume is under the Button.click event code right ?  Plus my boss just wanted me to add another feature "he is killin me" because he said that when he prints out the text file sometimes if the file name is to long, when he prints it out it will not all fit on one page. So he wants me to add a text box that allows the user to type inhow long he/she wants the files paths listed in the TXT file to be.  He is killing me with all of these add ons to this app. I would have to add that to every line of code that produced output right ? or could I like bring that logic in after I produce the final output file and then restrict the length of that output file to the numeric value in the textbox, then send it to the text file, that way I would only have to code for that functionality once...
0
 

Author Comment

by:vvandevender
ID: 19601052
Dale,

Also what would be the Textbox1.Text code to add subfolders, i see how to do the filenames, but also one of the checkboxes that can be checked add SubFolders to the textfile as well.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19601080
I handled the subfolders issue in my submission:

    Private IncludeSubdirectories As Boolean = True

So you set the IncludeSubdirectories variable to true/false and it gets passed in to the GetFiles() method:

    GetFiles(di, files, IncludeSubdirectories)

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19601157
As for the printing issue...

Do you want to:

(1) Generate a flat file, with truncated data, and then print that file.

(2) Print the data from within your app using the PrintDocument class:
http://msdn2.microsoft.com/en-us/library/system.drawing.printing.printdocument(VS.71).aspx
You can then render the path with ellipses in it using DrawString and the StringFormat.EllipsisPath option:
http://msdn2.microsoft.com/en-us/library/system.drawing.stringtrimming.aspx
You essentially then have to render each row, and each page using Graphics methods.
The complexity factor will go waaaaaaaaaaay up.....  =\
0
 

Author Comment

by:vvandevender
ID: 19602760
I want to generate a flat file with truncated data yes. After the file is produced in the directory they choose, then they decide what they want to do with it and my app is done. My app does not print it for them. After the file gets created, they just go to it through my computer and use Notepad to open the file and they do what they want with it.
0
 

Author Comment

by:vvandevender
ID: 19604256
In dale's code how would you bring in the sub folders when the user clicks on it. I am going with his approach with the select case.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19604319
0
 
LVL 2

Expert Comment

by:drekow
ID: 19604805
What I did was call the directoryinfo before pulling the files out of the same folder and loaded the names of the subdirectories into a string variable and then wrote the string to the textbox before writing the files. You could do a check before hitting the select case to see if the that checkbox is checked and if so then write the subdirectories to the file before the files get written.

Dim d As System.IO.DirectoryInfo

textbox1.text = "Directories for current folder" & vbNewLine

For Each folders As String In My.Computer.FileSystem.GetDirectories(folder)

      d = New System.IO.DirectoryInfo(folders)

      textbox1.text &= d.Name & vbNewLine

Next

Put that code inside an if statement before you search for the files in the chosen directory.

if somecheckbox.checked then
       write subdirectories
end if

Hope that helps.
0
 

Author Comment

by:vvandevender
ID: 19609064
Idle Mind that code you are telling me to work with does not have the checkbox functionality in it right? I only see code handling the sort is that correct or am I am i just missing code in there that handles all the checkbox possibilities? There are 7 checkboxes in the application that can be checked in any combination the user wants so you have to code for every possible output there. Plus the sort buttons that you have in your code.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19609331
No...there is no GUI on it.  As I said before, "I'll let you tie it all together with a pretty GUI though."  All you need to do is modify how the code is called based on the options the user has selected.  This isn't that difficult...for instance, just change the sort variable "mySortOrder" bases on what RadioButton has been selected.

I'm sure you can combine the two approaches.

It demonstrates several things though:

(1) Optional recursive directory searching allowing all subfolders (no matter how deep) to be iterated.

(2) Sorting

(3) How to get the different pieces of information about each file using the FileInfo class.

Here is the fundamental difference between the two approaches:

(A) The methods in My.Computer.FileSystem, GetFiles() and GetDirectories(), return an Array of String containing full paths, which means you have to either use static methods in System.IO.Path to extract information about the files <or> create an instance of FileInfo or DirectoryInfo from each path.  The GetFiles() and GetDirectories() methods also have the ability to recurse into subfolders by using the second parameter...but this is a blocking call.  If you do a recursive search at a fairly high level in the directory structure this could take awhile causing your app to freeze and become unresponsive.  The only way to fix this would be to move the code into a seperate thread, either thru the BackgroundWorker contol or by exclusively creating a new Thread.

(B) The approach I am using starts by creating an instance of DirectoryInfo from the root path.  Then when I call GetFiles(), it returns an Array of FileInfo instances (as opposed to an Array of String as in the approach above).  This allows us get the information about each file directly because it has been encapsulated into the class.  If subfolders are to be searched, we call GetDirectories and make a recursive call into each subfolder.  Since we are using manual recursion, we can simply add a call to Application.DoEvents() and keep the GUI responsive without the need for a seperate thread as in the approach above.
0
 

Author Comment

by:vvandevender
ID: 19610121
Idle Mind I am giving your approach a try. I have the core in my code and now I am attempting to tie the checkboxes in with it.

Say the user selects checkbox1(include files) and checkbox3(include paths) and chooses to sort by extension by clicking on radiobutton2  how would I tie that into your code you showed me. I think if I can get an example of how to tie these checkboxes and radiobuttons (sorts) in with it I could get it going.
0
 

Author Comment

by:vvandevender
ID: 19610296
Keep in mind that choosing to click on Checkbox1 and Checkbox 3 is only one of over 30 different combinations the user can select through the 7 checkboxes.
0
 

Author Comment

by:vvandevender
ID: 19612856
Idlemind,

looking at your code for the sorts. In this application the user selects the sort method he/she wants via radiobuttons. The user can select only one. It looks like you are hardcoding a value (sortby.name) and forcing the application to use that. The user selects this by secting the appropriate radio button.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19613629
Yes...so handle the RadioButton events and change the value of the "mySortOrder" variable accordingly!

Something like:

    Private Enum SortBy
        Name
        Extension
        Size
        LastWrite
    End Enum

    Private mySortOrder As SortBy = SortBy.Name

    Private Sub RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbSortByName.CheckedChanged, rbSortByExtension.CheckedChanged, rbSortByLength.CheckedChanged, rbSortByLastWrite.CheckedChanged
        Dim rb As RadioButton = CType(sender, RadioButton)
        If rb.Checked = True Then
            If rb Is rbSortByName Then
                mySortOrder = SortBy.Name
            ElseIf rb Is rbSortByExtension Then
                mySortOrder = SortBy.Extension
            ElseIf rb Is rbSortByLength Then
                mySortOrder = SortBy.Size
            Else
                mySortOrder = SortBy.LastWrite
            End If
        End If
    End Sub

Voila!  Now the sort order is "user customizeable"...

*** Note that the RadioButton_CheckedChanged() sub Handles ALL FOUR RadioButton CheckChanged() events by listing them all after the "Handles" keyword. ***
0
 

Author Comment

by:vvandevender
ID: 19616939
Since I am using this code directly above will I still need all my private functions that you showed me earlier ?

Example:  
  Private Function SortByName(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiA.Name.CompareTo(fiB.Name)
    End Function

    Private Function SortByExtension(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        If fiA.Extension <> fiB.Extension Then
            Return fiA.Extension.CompareTo(fiB.Extension)
        Else
            Return fiA.Name.CompareTo(fiB.Name)
        End If
    End Function

    Private Function SortBySize(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiA.Length.CompareTo(fiB.Length)
    End Function

    Private Function SortByLastWrite(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiA.LastWriteTime.CompareTo(fiB.LastWriteTime)
    End Function
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19617688
Of course you will...those tell the Sort() method how to compare the items.

The code above was just to demonstrate how to change the sort order variable.

You would add the code below to the code I submitted earlier:

    Private Sub RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbSortByName.CheckedChanged, rbSortByExtension.CheckedChanged, rbSortByLength.CheckedChanged, rbSortByLastWrite.CheckedChanged
        Dim rb As RadioButton = CType(sender, RadioButton)
        If rb.Checked = True Then
            If rb Is rbSortByName Then
                mySortOrder = SortBy.Name
            ElseIf rb Is rbSortByExtension Then
                mySortOrder = SortBy.Extension
            ElseIf rb Is rbSortByLength Then
                mySortOrder = SortBy.Size
            Else
                mySortOrder = SortBy.LastWrite
            End If
        End If
    End Sub
0
 

Author Comment

by:vvandevender
ID: 19617898
And I would also still need the select case below to call those functions after I click button 1 right?  So I will need all the functions, the select case, and the Radiobutton routine directly above to make the sort work right ?

Select Case mySortOrder
                Case SortBy.Name
                    files.Sort(AddressOf Me.SortByName)

                Case SortBy.Extension
                    files.Sort(AddressOf Me.SortByExtension)

                Case SortBy.Size
                    files.Sort(AddressOf Me.SortBySize)

                Case SortBy.LastWrite
                    files.Sort(AddressOf Me.SortByLastWrite)

            End Select

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19618696
Correct...you need everything there was before as that is the "engine" of the system.  Then you simply add code to handle the GUI elements and change the variables that control how the "engine" handles the data.
0
 

Author Comment

by:vvandevender
ID: 19619599
I got the sorts working.. thanks man.. now I am working on the checkboxes, I may run into a wall with them since there are so many diffrent combinations of output they can choose from, but I will let you know if I do. . When this is all said and done is there a way I can give more than 500 points for this question ??? You and dale have been worth well over 500 points for this one... Let me know how we can do that because I really want to give you two guys many more points than 500..
0
 

Author Comment

by:vvandevender
ID: 19620141
Idlemind

For my checkbox scenerios, do I code all of these in my getfiles sub routine here below

Private Sub GetFiles(ByVal di As System.IO.DirectoryInfo, ByVal fileList As List(Of System.IO.FileInfo), ByVal IncludeSubdirectories As Boolean)
        fileList.AddRange(di.GetFiles())
        If IncludeSubdirectories Then
            For Each subDi As System.IO.DirectoryInfo In di.GetDirectories
                GetFiles(subDi, fileList, IncludeSubdirectories)
            Next
        End If

Or would I code it in the clickbutton1 sub routine?

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19620482
500 is supposed to be the limit...and I think it's plenty.

For the CheckBoxes, you don't put that logic into the GetFiles() method.  The GetFiles() method only retrieves the files and puts them into a List.

The CheckBoxes come into play AFTER the Sort...when you are outputting the data into a file.

So you:

(1) Retrieve all the files (optionally recursively).
(2) Sort the files.
(3) Output the sorted data in your desired format.

See my comments back at this post:
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22723568.html#19594620
0
 

Author Comment

by:vvandevender
ID: 19624679
The getfiles() method looks like it is coded to retrieve the files, but it looks like it assumes that the checkbox (include subfolders) will be checked everytime and that is not true. It does not have to be checked everytime it is just an option the user has.  What do i do if the user does not check (include subfolders) and the user selects one of the other 20 different combinations. The logic needs to be there to handle both situations.
0
 

Author Comment

by:vvandevender
ID: 19624696
Here is the code I have right now in the click button1 event (i call it gobutton) and also my getfiles() method. Maybe this will help by showing you what i have right now..

 Private Sub GoBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GoBtn.Click
        Try
            Dim folder As String = DirListBox1.DirList(DirListBox1.DirListIndex)
            files = New List(Of System.IO.FileInfo)
            Dim di As New System.IO.DirectoryInfo(folder)
            If ChkSubFolders.Checked And ChkIncludeFiles.Checked Then
                GetFiles(di, files, IncludeSubdirectories)
            End If
            Select Case mySortOrder
                Case SortBy.Name
                    files.Sort(AddressOf Me.SortByName)

                Case SortBy.Extension
                    files.Sort(AddressOf Me.SortByExtension)

                Case SortBy.Size
                    files.Sort(AddressOf Me.SortBySize)

                Case SortBy.LastWrite
                    files.Sort(AddressOf Me.SortByLastWrite)

            End Select

            Dim outputFile As String = OutputTxt.Text
            Dim sw As New System.IO.StreamWriter(outputFile)
            If RadioName.Checked Then
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))

            ElseIf RadioName.Checked = False And RadioExtension.Checked = False And RadioSize.Checked = False And RadioDate.Checked = False Then
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))

            End If
            GetFiles(di, files, IncludeSubdirectories)
            If ChkIncludeFiles.Checked = True And ChkFullPaths.Checked = True Then
                For Each fi As System.IO.FileInfo In files
                    sw.WriteLine(fi.FullName)
                Next
            End If



            Dim lastdirectoryname As String = folder
            For Each fi As System.IO.FileInfo In files
                If Strings.Left(fi.FullName, Strings.InStrRev(fi.FullName, "\") - 1) <> lastdirectoryname Then
                    lastdirectoryname = fi.DirectoryName

                    sw.WriteLine()
                    sw.WriteLine(fi.DirectoryName)
                    sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(fi.DirectoryName)), " ", "="))
                    sw.WriteLine()
                End If
                sw.WriteLine(fi.Name)

            Next
            sw.Close()
            Process.Start(outputFile)

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        End Try

    End Sub
    Private Sub GetFiles(ByVal di As System.IO.DirectoryInfo, ByVal fileList As List(Of System.IO.FileInfo), ByVal IncludeSubdirectories As Boolean)
        fileList.AddRange(di.GetFiles())
        Dim outputFile As String = OutputTxt.Text
        If ChkSubFolders.Checked = True And ChkIncludeFiles.Checked = True Then
            For Each subDi As System.IO.DirectoryInfo In di.GetDirectories
                GetFiles(subDi, fileList, IncludeSubdirectories)

            Next
        End If


    End Sub
 

Private Sub GetFiles(ByVal di As System.IO.DirectoryInfo, ByVal fileList As List(Of System.IO.FileInfo), ByVal IncludeSubdirectories As Boolean)
        fileList.AddRange(di.GetFiles())
        Dim outputFile As String = OutputTxt.Text
        If ChkSubFolders.Checked = True And ChkIncludeFiles.Checked = True Then
            For Each subDi As System.IO.DirectoryInfo In di.GetDirectories
                GetFiles(subDi, fileList, IncludeSubdirectories)

            Next
        End If



0
 

Author Comment

by:vvandevender
ID: 19625845
Well guys I got if figured out. I am not done coding everything but It all is coming together and it is going work fine.

I have one question though is there a way to make the code below write to the text file in a column format. Nothing lines up and it looks bad, i was wondering if there was a line of code I could add below it or above it or some code I could add to the actual line of code istelf to make this happen.
sw.WriteLine(fi.Name & "," & fi.Length & "," & fi.LastWriteTime & "," & fi.FullName)

Also my boss wants a text box created that allows the user to type a number in it and that number will be the length of each line in the text file ? He said that when he prints off the pages some of the foldernames and filenames are so long that it wont fit on the page of print. I have the text box created and it's called TxtMaxLength.

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19625924
See String.PadRight():
http://msdn2.microsoft.com/en-us/library/34d75d7s.aspx

So instead of:

    fi.Name

You would use something like:

    fi.Name.PadRight(30)
0
 

Author Comment

by:vvandevender
ID: 19626121
Why cant I pad right on Fi.length and fi.lastwriteTime? I need to do it there too...
0
 

Author Comment

by:vvandevender
ID: 19626159
Nevermind I figured it out ha ha i converted it to string.. and it worked.. i did this:

fi.length.tostring.padright(30)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19627393
Yay!....you seem to be getting more comfortable with VB.Net coding...  ;)
0
 

Author Comment

by:vvandevender
ID: 19627481
I have learned a lot by this application thanks to you guys!!! I like it much better than the mainframe. Debugging is much simpler because you can see your values on the fly as apposed to having to expedite your cobol code. Expedite is our Mainframe debugging tool we have here at work.

Is it hard to make a message box do a count in visual basic?  I need a message box to pop up that tells the user how many folders and files that are going to written in the txt file. I was going to add it write before the Sw.Close line of code. So it will display before the output process is started. That may be a wrong approach here but I was just guessing. I could add it in each of my if statements so i will keep a count of the current if statement.  How would you handle this idle mind???
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19627536
The "files" List will have a count of everything right?

So make your up "msg" and then display it:

    Dim msg As String = files.Count & " entries written to " & outputFile
    MessageBox.Show(msg, "Done")
    Process.Start(outputFile)
0
 

Author Comment

by:vvandevender
ID: 19627947
Works like a charm...

Any suggestions on how to approch the text box I talked about above:

Also my boss wants a text box created that allows the user to type a number in it and that number will be the length of each line in the text file ? He said that when he prints off the pages some of the foldernames and filenames are so long that it wont fit on the page of print. I have the text box created and it's called TxtMaxLength.


0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19628215
Again, see my comments back at this post:
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22723568.html#19594620

Then after building up the output string, just truncate it if necessary:

        Dim output As String
        For Each fi As System.IO.FileInfo In files  
            output = ""
            If something Then
                output = fi.Name.PadRight(xxxx)
            End If
            If somethingElse Then
                output = output & "," & fi.Length.ToString.PadLeft(15)
            End If
            etc...

            ' Truncate the output if necessary...
            If output.Length > maxLength Then
                output = output.Substring(0, maxLength)
            End If

            sw.WriteLine(output)
        Next

Also, I would recommend using a NumericUpDown control instead of a TextBox for the "max length value".
0
 

Author Comment

by:vvandevender
ID: 19628324
Would the "something" be the NumericUpDown Control value ?
0
 

Author Comment

by:vvandevender
ID: 19628337
Oh nevermind it would be the checkboxes checked.. I get it now...
0
 

Author Comment

by:vvandevender
ID: 19628349
I would just add that truncating code to all of my if statements that I already have right?
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 19628426
It depends on how you wrote it...

I "built" the line using a variable called "output" and then only needes ONE call to sw.WriteLine() at the bottom.
0
 

Author Comment

by:vvandevender
ID: 19640795
Back to the files count in the message box. The files count is working great I also need to add a folder count as well and when I added the "folders.count" it did not work it gave me an error. I was wondering if you knew a way to make this work idle mind. I need both counts to display in that one message box.
0
 

Author Comment

by:vvandevender
ID: 19640811
Here is all my code in the Gobutton click event where everything takes place. I also included the getfiles methods since it is being called by the Gobutton click event..

   Private files As List(Of System.IO.FileInfo)
    Private folders As List(Of System.IO.DirectoryInfo)
    Private IncludeSubdirectories As Boolean = True

    Private Sub GoBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GoBtn.Click
        Try
            Dim folder As String = DirListBox1.DirList(DirListBox1.DirListIndex)
            files = New List(Of System.IO.FileInfo)
            Dim di As New System.IO.DirectoryInfo(folder)
            Dim outputFile As String = OutputTxt.Text
            Dim sw As New System.IO.StreamWriter(outputFile)


            If ChkSubFolders.Checked And ChkIncludeFiles.Checked And ChkFullPaths.Checked = False Then
                GetFiles(di, files, IncludeSubdirectories)
                Dim lastdirectoryname As String = folder
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))
                For Each fi As System.IO.FileInfo In files
                    If Strings.Left(fi.FullName, Strings.InStrRev(fi.FullName, "\") - 1) <> lastdirectoryname Then
                        lastdirectoryname = fi.DirectoryName

                        sw.WriteLine()
                        sw.WriteLine(fi.DirectoryName)
                        sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(fi.DirectoryName)), " ", "="))
                        sw.WriteLine()
                    End If
                    sw.WriteLine(fi.Name)

                Next
            End If

            If ChkIncludeFiles.Checked = True And ChkFullInfo.Checked = True Then

                GetFiles(di, files, IncludeSubdirectories)
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))
                For Each fi As System.IO.FileInfo In files
                    sw.WriteLine(fi.Name.PadRight(35) & fi.Length.ToString.PadRight(15) & fi.LastWriteTime)
                Next
            End If


            If ChkSubFolders.Checked And ChkIncludeFiles.Checked = False Then
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))
                For Each subdi As System.IO.DirectoryInfo In di.GetDirectories
                    If subdi.FullName <> subdi.FullName Then




                    End If
                    sw.WriteLine(subdi.Name)



                Next

            End If

            If ChkIncludeFiles.Checked And ChkFullPaths.Checked = False And ChkFullInfo.Checked = False Then
                GetFiles(di, files, IncludeSubdirectories)
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))
                For Each fi As System.IO.FileInfo In files
                    sw.WriteLine(fi.Name)

                Next

            End If
            Select Case mySortOrder
                Case SortBy.Name
                    files.Sort(AddressOf Me.SortByName)

                Case SortBy.Extension
                    files.Sort(AddressOf Me.SortByExtension)

                Case SortBy.Size
                    files.Sort(AddressOf Me.SortBySize)

                Case SortBy.LastWrite
                    files.Sort(AddressOf Me.SortByLastWrite)

            End Select



            'If RadioName.Checked Then
            '    sw.WriteLine(folder)
            '    sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))

            'ElseIf RadioName.Checked = False And RadioExtension.Checked = False And RadioSize.Checked = False And RadioDate.Checked = False Then
            '    sw.WriteLine(folder)
            '    sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))

            'End If

            If ChkIncludeFiles.Checked = True And ChkFullPaths.Checked = True Then
                GetFiles(di, files, IncludeSubdirectories = False)
                For Each fi As System.IO.FileInfo In files
                    If (fi.FullName.Length) > MaxFilelength.Value Then
                        sw.WriteLine(fi.FullName.Substring(0, MaxFilelength.Value))

                    Else
                        sw.WriteLine(fi.FullName)

                    End If

                Next




            End If

            Dim msg As String = folders.Count & files.Count & " entries written to " & outputFile
            MessageBox.Show(msg, "Done")

            sw.Close()
            Process.Start(outputFile)


        Catch ex As Exception
            MessageBox.Show(ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        End Try

    End Sub
   


 Private Sub GetFiles(ByVal di As System.IO.DirectoryInfo, ByVal fileList As List(Of System.IO.FileInfo), ByVal IncludeSubdirectories As Boolean)
        fileList.AddRange(di.GetFiles())
        If ChkSubFolders.Checked = True And ChkIncludeFiles.Checked = True And ChkFullPaths.Checked = False Then
            For Each subDi As System.IO.DirectoryInfo In di.GetDirectories
                GetFiles(subDi, fileList, IncludeSubdirectories)

            Next
        End If


    End Sub

0
 

Author Comment

by:vvandevender
ID: 19641371
Another thing I noticed is that my sorts are not working, could that be because I am calling the get files method everytime I do a if statement ?
0
 

Author Comment

by:vvandevender
ID: 19646404
I got my sorts working so thats done, It had to do with the fact that I was calling the get files method everytime i was performing  a if statement.

I have everything working now except the folders count in the message box and my max file size limiter. I have the files count working fine, but the folders count is giving me fits. I am also having trouble getting the file length limiter (numericupdownbox) to work when I am using a subfolders. It works fine when no subfolders are being used.

Idle mind,
How would you make the maxfilelimit box work in this scenario below?
 If ChkSubFolders.Checked And ChkIncludeFiles.Checked And ChkFullPaths.Checked And ChkFullInfo.Checked Then
                Dim lastdirectoryname As String = folder
                sw.WriteLine(folder)
                sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(folder)), " ", "="))
                For Each fi As System.IO.FileInfo In files
                    If Strings.Left(fi.FullName, Strings.InStrRev(fi.FullName, "\") - 1) <> lastdirectoryname Then
                        lastdirectoryname = fi.DirectoryName

                        sw.WriteLine()
                        sw.WriteLine(fi.DirectoryName)
                        sw.WriteLine(Strings.Replace(Strings.Space(Strings.Len(fi.DirectoryName)), " ", "="))
                        sw.WriteLine()
                    End If
                    sw.WriteLine(fi.FullName.PadRight(200) & fi.Length.ToString.PadRight(30) & fi.LastWriteTime)

                Next
            End If


0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question