Change the name of a File?

DevilAkuma

Active member
Joined
Oct 24, 2005
Messages
37
Programming Experience
Beginner
Hello!

It's possible to change the name of a File? My problem is that I want to change file.txt to file.xls. If I use File.copy(.../file.txt, .../file.xls) and after that erase the first file, some values are changed. Values relationated with dates...

Is is possible ONLY to change the extension?

Thanks in advance!
 
If you'd like to stay away from the Microsoft.VisualBasic namespace you would use System.IO.File.Move(sourceFileName, destFileName).
Some would argue that the Microsoft.VisualBasic namespace may not be in future releases.
 
In documentation for Microsoft.VisualBasic.Filesystem module they recommend to use the new My.Computer.FileSystem object instead. There are several new .Net 2.0 namespaces under Microsoft.VisualBasic among them the MY services. Paszt suggestion about System.IO namespace is of course also perfectly valid.
 
And to throw a third option into the mix, you can additionally use System.IO.FIleInfo().MoveTo()

How this differs to Paszt's suggestion is that you need to create an instance of FileInfo first, whereas File.Move is a static method. i.e. you would only use FileInfo.MoveTo if you wanted to do some other things with the FileInfo first..

The following link provides a breakdown of how to do common IO tasks:
http://msdn2.microsoft.com/en-us/library/ms404278.aspx
 
you can always use System.IO.Directory.GetFileSystemEntries("Directory path") then loop through the collection renameing each one
 
This is done easily when youn know the file names. What about if you have 300+ files that need to be changed from .dat to .txt ???

Any takers?

Jose:cool:


Open a dos window and type:

REN *.DAT *.TXT


in vb:

VB.NET:
Dim files() as FileInfo = New DirectoryInfo("C:\temp").GetFiles("*.dat")
foreach fi as FileInfo in files
  fi.MoveTo(fi.Name.Replace(fi.Extension, ".txt"))
next fi
 
Tut, tut cjard. Didn't you rep me for steering you to the File class over the FileInfo class?
VB.NET:
For Each filePath As String In IO.Directory.GetFiles("folder path here", "*.dat")
    IO.File.Move(filePath, IO.Path.ChangeExtension(filePath, ".txt"))
Next filePath
I don't know why this would have been posted in Windows Forms in the first place either. Moved.
 
Back
Top