简体   繁体   中英

How to rename files that contain specific text string?

Im a newbie programmer writing my first application in VB in VS2010. I am working with a directory containing multiple XML files. I have written some code that converts the file extensions from .xml to .txt, which is the intent of my app, however, I'm not sure how to specify criteria for this code to execute. What I am really trying to acheive is having my application loop through the entire directory and change the file extension for ONLY those xml files that contain a specific text string, like "TEST FILE" within one of the xml nodes. The XML schemas are all the same and the files are all relatively small (between 2 & 5kb each), but there are several thousands of them within my target directory. Any tips/suggestions for how I can accomplish this? Here is the code I have so far. Thanks!

    Dim [option] As SearchOption = SearchOption.AllDirectories
    [option] = SearchOption.AllDirectories
    Dim files As String()
    files = Directory.GetFiles("U:\Primitive_XMLs", "*.xml", [option])
    Dim filepath_new As String
    For Each filepath As String In files

        filepath_new = filepath.Replace(".xml", ".txt")
        System.IO.File.Move(filepath, filepath_new)
    Next

if the files are indeed small, and you dont need to specify a certain node (eg the presence of the string anywhere in the file is enough to warrant moving it) you can try the following

    Dim mustContain As String = "TEST FILE"
    Dim files As String() = IO.Directory.GetFiles("U:\Primitive_XMLs", "*.xml", IO.SearchOption.AllDirectories)
    For Each filepath As String In files
        If IO.File.ReadAllText(filepath).Contains(mustContain) Then
            IO.File.Move(filepath, filepath.Replace(".xml", ".txt"))
        End If
    Next

If you do need to specify where this string can be found (eg only move file if the 3rd node contains it) then you will need to parse the file, using something like the xmlreader class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM