Solved

Search files in file system

Posted on 2012-03-15
11
275 Views
Last Modified: 2012-03-19
I need help with searching files in a folder with a name like for example I have an xml file 20120068.007.xml and I need to search all files which are 20120068.007.03.pdf, 20120068.007.04.pdf and 20120068.007.05.pdf using vb.net code and store those files names in a list or something and move them as well as the xml to a seperate folder
0
Comment
Question by:welcome 123
  • 4
  • 4
  • 2
  • +1
11 Comments
 
LVL 17

Expert Comment

by:nepaluz
ID: 37726465
try
Dim FileShadow = "20120068.007.xml".Split(".")
Dim SearchPattern As String = FileShadow(0) & FileShadow(1) & "*.pdf"
Dim Result = Directory.GetFiles("FolderPath", SearchPattern)

Open in new window

0
 
LVL 25

Accepted Solution

by:
SStory earned 500 total points
ID: 37726518
    Sub DoIt(FolderPath As String)
        Dim Files As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(FolderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.xml")
        For Each strFile As String In Files
            'get all files with that prefix
            Dim FilePrefix As String = strFile.Substring(0, 12)
            Dim OtherFiles As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(FolderPath, FileIO.SearchOption.SearchTopLevelOnly, FilePrefix & ".*")
            Dim bCreatedFolder As Boolean = False
            For Each strRelatedFile As String In OtherFiles
                If strRelatedFile.Substring(strRelatedFile.Length - 4, 4).ToUpper <> ".XML" Then
                    'if not the XML file handle it
                    If bCreatedFolder Then
                        'folder exists

                        'move the file to c:\temp\whatever
                        My.Computer.FileSystem.MoveFile(strRelatedFile, "c:\temp\" & strRelatedFile, True)
                    Else
                        'make a folder for it
                        MkDir("c:\Temp\" & FilePrefix)
                        bCreatedFolder = True
                    End If
                End If
            Next
            'done getting other files, so move the xml file itself
            If bCreatedFolder Then
                'folder exists

                'move the xml file to c:\temp\whatever
                My.Computer.FileSystem.MoveFile(strFile, "c:\temp\" & strFile, True)
            Else
                'make a folder for it
                MkDir("c:\Temp\" & FilePrefix)
                bCreatedFolder = True
            End If
        Next
    End Sub

Open in new window


Change the c:\temp references to wherever you want to place the folders.  This has not been tested, but should give you the general idea.
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37726529
Using the code given by nepaluz and fetching some from msdn...
here is a solution for you...

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Try
            ' Only get files that begin with the letter "c."
            Dim FileShadow = "20120068.007.xml".Split(".")
            Dim SearchPattern As String = FileShadow(0) & FileShadow(1) & "*.pdf"
            Dim dirs As String() = Directory.GetFiles("c:\", searchpattern)
            Console.WriteLine("The number of files found are {0}.", dirs.Length)
            Dim dir As String
            For Each dir In dirs
                Console.WriteLine(dir)
                Directory.Move(dir,"c:\NewPath\")
            Next
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Open in new window

0
 

Author Comment

by:welcome 123
ID: 37731151
Well I tried both the codes given above and in the code given by sstory everything works but for I am unable to move the file  with the same name as in the code below:

when using My.Computer.FileSystem.MoveFile(strRelatedFile, str, True)
the str is taking a folderpath and it should take file path and the str related path does take the complete file path with filename i.e C:\Move\20110290.030.04.pdf

I want to move the file to C:\Temp\20110290.030.04.pdf
 or C:\Temp\20110290.030\20110290.030.04.pdf

  and also when I try the code given by Buggycode or nepaulz it failes to get any results in the dir as shown below after the cpde given by sstory

Sub DoIt(ByVal FolderPath As String)
        Try
            Dim Files As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(FolderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.xml")
            For Each strFile As String In Files
                'get all files with that prefix
                Dim FilePrefix As String = strFile.Substring(8, 12)
                Dim OtherFiles As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(FolderPath, FileIO.SearchOption.SearchTopLevelOnly, FilePrefix & ".*.PDF")
                Dim bCreatedFolder As Boolean = False
                For Each strRelatedFile As String In OtherFiles
                    If strRelatedFile.Substring(strRelatedFile.Length - 4, 4).ToUpper <> ".XML" Then
                        'if not the XML file handle it
                        ' If bCreatedFolder Then
                        'folder exists
                        Dim str As String = "C:\temp\" & FilePrefix & "\"
                        'move the file to c:\temp\whatever
                        My.Computer.FileSystem.MoveFile(strRelatedFile, str, True)
                        'Directory.Move(strRelatedFile, str)

                        'Else
                        '    'make a folder for it
                        '    MkDir("c:\Temp\" & FilePrefix)
                        '    bCreatedFolder = True
                        'End If
                    End If
                Next
                'done getting other files, so move the xml file itself
                If bCreatedFolder Then
                    'folder exists

                    'move the xml file to c:\temp\whatever
                    My.Computer.FileSystem.MoveFile(strFile, "c:\temp\" & strFile, True)
                Else
                    'make a folder for it
                    MkDir("c:\Temp\" & FilePrefix)
                    bCreatedFolder = True
                End If
            Next
        Catch ex As Exception
        End Try

    End Sub



Sub somemore()

        Try
            ' Only get files that begin with the letter "c."
            Dim FileShadow = "20110290.030.xml".Split(".")
            Dim SearchPattern As String = FileShadow(0) & FileShadow(1) & ".*.pdf"
            Dim dirs As String() = Directory.GetFiles("c:\Move", SearchPattern)

'dirs returns 0 even though has 3 files
            Console.WriteLine("The number of files found are {0}.", dirs.Length)
            Dim dir As String
            For Each dir In dirs
                Console.WriteLine(dir)
                Directory.Move(dir, "c:\temp\")
            Next
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try

    End Sub
0
 
LVL 25

Expert Comment

by:SStory
ID: 37731344
I assume you mean you can move all of the files but the XML file is that right?
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:welcome 123
ID: 37734023
No, Its not about not able to move other files and XML, I am able to get the files in the search in the strrelated file collection with its complete path but when I try to do file move the destination location only accepts the filename alonmg with path so I have to do a substring again to get the filename from the collection that means I need to hard code the path but cannot give the path in webconfig and take it etc


Is there any way we can move files in a directory without specifying a filename i.e

My.Computer.FileSystem.MoveFile("C"\test.pdf", "C:\temp")
0
 
LVL 25

Expert Comment

by:SStory
ID: 37737350
I assumed that you knew something about programming. Am I wrong? If so I assumed you'd know that you could rewrite the code anyway you wanted. The "C:\temp" was just there, you could add another parameter to the Sub routine call that is the destination folder and use that instead of C:\temp.  Do you not know how to do that?
0
 

Author Comment

by:welcome 123
ID: 37737522
well i think you totally got me wrong here I do know programming and also do appreciate your solution. I was just trying to see if there is any function without using any substring to get the filename if there is any function that you can move a file to a directory instead of specifying a filename , was just asking but i think i didn't know how to say this exactly. anyways i used substring and retrieved the filename and also re wrote the code.

Thanksa lot. everything worked the way i wanted to.
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37737526
hi sailaja123,

Please close this question...

Happy Programming
0
 

Author Comment

by:welcome 123
ID: 37737532
Also sice I used sstrory code to test which worked i a going to close this and had i used nepauz it would also have worked maybe i would have done a little tweeks here and there, so i aplozise nepaulz for giving the entire credit to sstory as his code was very detailed which worked for me without spending any extra time etc.
0
 
LVL 25

Expert Comment

by:SStory
ID: 37738322
OK, well I wasn't trying to insult you but trying to gauge your experience level since it seemed you were hung on the literal string "c:\temp"

Of course here is the system.io.fileinfo class that can break a filename apart if that is what you want to do.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video discusses moving either the default database or any database to a new volume.

760 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now