Renaming files in a directory

Camus

Active member
Joined
Oct 4, 2007
Messages
28
Programming Experience
Beginner
The software I'm using at the moment outputs .txt files, which I then have to rename manually to a .csv.
Sometimes that involves renaming 30 or so files, which takes a while.

How would I go about writing something in Visual Basic Express that would rename all the the files to have a .csv extension rather than a .txt?

Also, as far as the interface is concerned, I'm guessing I would need to have a way of first selecting the folder that the txt files are in, and then just a button to rename the .txts?

Hope someone can help.
 
try this

VB.NET:
Dim dir As DirectoryInfo = New DirectoryInfo(your directory name)
Dim fileinfo As FileInfo

For Each fileinfo In dir.GetFiles
     If fileinfo.Extension.ToLower = ".txt" Then
        fileinfo.MoveTo(fileinfo.FullName.Substring(0, fileinfo.FullName.Length - 4) & ".csv")
     End If
Next
 
VB.NET:
    Dim dir As DirectoryInfo = New DirectoryInfo(your directory name)

    For Each fileinfo As FileInfo In dir.GetFiles
     If fileinfo.Extension.ToLower = ".txt" Then
        fileinfo.MoveTo(System.IO.Path.GetFileNameWithoutExtension(fileinfo.FullName) & ".csv")
     End If
Next
 
JuggaloBrotha's code will lose your files! it hasn't got a file path in the .moveto statement

VB.NET:
    Dim dir As DirectoryInfo = New DirectoryInfo(your directory name)
 
    For Each fileinfo As FileInfo In dir.GetFiles
     If fileinfo.Extension.ToLower = ".txt" Then
        fileinfo.MoveTo(System.IO.Path.GetFileNameWithoutExtension(fileinfo.FullName) & ".csv")
     End If
    Next

i forgot to mention

VB.NET:
imports system.io
Imports System.Text

so

VB.NET:
Dim dir As DirectoryInfo = New DirectoryInfo(your directory name)

For Each fileinfo As FileInfo In Dir.GetFiles
     If fileinfo.Extension.ToLower = ".txt" Then
        Dim sb As New StringBuilder
        sb.Append(Path.GetDirectoryName(fileinfo.FullName))
        sb.Append("\")
        sb.Append(Path.GetFileNameWithoutExtension(fileinfo.FullName))
        sb.Append(".csv")
        fileinfo.MoveTo(sb.ToString)
     End If
Next
 
Last edited:
VB.NET:
For Each fullname As String In IO.Directory.GetFiles("d:\somepath", "*.txt")
    IO.File.Move(fullname, IO.Path.ChangeExtension(fullname, ".csv"))
Next
 
Back
Top