
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
680
|
Chapter 12: Filesystem I/O
File class or the instance MoveTo method of the FileInfo class. The static File.Move
method can be used to rename a file in the following manner:
public static void RenameFile(string originalName, string newName)
{
File.Move(originalName, newName);
}
This code has the effect of renaming the originalName file to newName.
The
FileInfo.MoveTo instance method can also be used to rename a file in the follow-
ing manner:
public static void RenameFile(FileInfo originalFile, string newName)
{
originalFile.MoveTo(newName);
}
Discussion
The Move and MoveTo methods allow a file to be moved to a different location, but
they can also be used to rename files. For example, you could use
RenameFile to
rename a file from foo.txt to bar.dat:
RenameFile("foo.txt","bar.dat");
You could also use fully qualified paths to rename them:
RenameFile("c:\mydir\foo.txt","c:\mydir\bar.dat");
See Also
See the “File Class” and “FileInfo Class” topics in the MSDN documentation.
12.4 Determining Whether a File Exists
Problem
You need to determine whether a file exists prior to creating or performing an action
on that file.
Solution
Use the static Exists method of the File class to determine whether a file currently
exists:
if (File.Exists(@"c:\delete\test\test.txt"))
{
// Operate on that file here.
}