
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
676
|
Chapter 12: Filesystem I/O
The Delete instance method on the FileInfo class takes no parameters and returns
void. For example, the following code uses the Delete instance method of the
FileInfo class to delete a file:
if(File.Exists(@"c:\delete\test\test.txt"))
{
FileInfo fileInfo = new FileInfo(@"c:\delete\test\test.txt");
fileInfo.Delete( );
}
Discussion
Whether you choose to call the static or instance file-operation methods depends on
what you are trying to accomplish. If you need a quick way of creating, moving,
copying, or deleting a file, consider using the static methods. If you will be perform-
ing multiple operations on a file, such as creating, moving, and changing its
attributes, you should consider the instance methods of the
FileInfo class. Another
consideration is that static methods on a class do not require an object to be created
on the managed heap and subsequently destroyed by the garbage collector. Instance
methods require an object to be created before the methods can be called. If you are
trying to minimize the number of objects the garbage collector has to manage, con-
sider using static methods.
A few items to note when using the file functions:
• If the directory doesn’t exist, the method won’t create it and you’ll get an excep-
tion. See how to check whether ...