1

我目前有这些要重命名的文件组:

C:\Users\tmedina\Documents\testenviroment\Testfolder\file1-1111.doc
C:\Users\tmedina\Documents\testenviroment\Testfolder\file2-1111.doc
C:\Users\tmedina\Documents\testenviroment\Testfolder\file3-1111.doc
...
C:\Users\tmedina\Documents\testenviroment\Testfolder\file20-1111.doc

我的表单上有一个文本框,我将在其中输入一个文本字符串,它将“1111”替换为文本框字段中的任何字符串。

因此,例如,在我的应用程序中,在文本框字段中,我会输入2222,然后当我单击 button1 时,它将重命名file1-1111.docfile1-2222.docfile2-1111.doctofile2-2222.doc等......

这是我目前拥有的 VB 代码:

Dim base As String = "C:\Users\tmedina\Documents\testenviroment\"
Dim newDir As String = base + CStr(TextBox1.Text)
Directory.CreateDirectory(newDir)
Directory.SetCurrentDirectory(newDir)
For Each nameChangeFiles As String In My.Computer.FileSystem.GetFiles(newDir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*1111*")
            My.Computer.FileSystem.RenameFile(nameChangeFiles, "2222")

但这只会创建一个名为 2222 的空白文件(没有扩展名)。

任何帮助将不胜感激。

4

4 回答 4

0

你可以试试这个。

For Each nameChangeFiles As String In My.Computer.FileSystem.GetFiles(newDir, SearchOption.SearchAllSubDirectories, "*1111*") 
    Dim newName As String = nameChangeFiles.Replace("1111", "2222")
    My.Computer.FileSystem.RenameFile(nameChangeFiles, newName) 
Next

但这总是将“1111”部分更改为“2222”。您说过您在文本框中输入了新字符串以替换“1111”,但在您上面的代码中,唯一存在的文本框用于创建子目录。
你能解释一下你从哪里得到替换文本吗?

于 2012-06-25T21:33:31.973 回答
0

尝试这个:

Dim base As String = "C:\Users\tmedina\Documents\testenviroment\"
Dim newDir As String = base + CStr(TextBox1.Text)

Directory.CreateDirectory(newDir)
Directory.SetCurrentDirectory(newDir)

For Each nameChangeFiles As String In My.Computer.FileSystem.GetFiles(newDir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*1111*")

    Dim fi As FileInfo
    fi = New FileInfo(nameChangeFiles)

    Dim newFilename As String = Path.Combine(newDir, fi.Name.Replace("1111", "2222"))
    My.Computer.FileSystem.RenameFile(nameChangeFiles, newFilename)

Next
于 2012-06-25T21:34:25.413 回答
0

使用 String.Replace() 函数:

Dim base As String = "C:\Users\tmedina\Documents\testenviroment\"
Dim newDir As String = base + CStr(TextBox1.Text)
Directory.CreateDirectory(newDir)
Directory.SetCurrentDirectory(newDir)
String ToReplace = "1111"

For Each nameChangeFiles As String In My.Computer.FileSystem.GetFiles(newDir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*" & ToReplace & "*")
            My.Computer.FileSystem.RenameFile(nameChangeFiles.Replace(ToReplace, "2222"))
于 2012-06-25T21:35:38.143 回答
0

RenameFile不知道要重命名文件的哪一部分;它只做整个事情。不管怎样,我是这样写的:

Dim newDir As String = Path.Combine(base, TextBox1.Text)

For Each f As FileInfo In New DirectoryInfo(base).GetFiles("*.doc", SearchOption.AllDirectories)
    f.CopyTo(Path.Combine(newDir, Regex.Replace(f.Name, "\d+\.doc$", "2222.doc")))
Next
于 2012-06-25T21:38:27.307 回答