
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
674
|
Chapter 12: Filesystem I/O
Unless otherwise specified, you need the following using statements in any program
that uses snippets or methods from this chapter:
using System;
using System.IO;
12.1 Creating, Copying, Moving, or Deleting a File
Problem
You need to create a new file, copy an existing file, move an existing file, or delete a
file.
Solution
The System.IO namespace contains two classes to perform these actions: the File and
FileInfo classes. The File class contains only static methods, while the FileInfo
class contains only instance methods.
File’s static Create method returns an instance of the FileStream class, which you
can use to read from or write to the newly created file. For example, the following
code uses the static
Create method of the File class to create a new file:
FileStream fileStream = null;
if (!File.Exists(@"c:\delete\test\test.txt"))
{
using(fileStream = File.Create(@"c:\delete\test\test.txt"))
{
// Use the fileStream var here...
}
}
The Create instance method of the FileInfo class takes no parameters. You should
supply the path with a filename as the only parameter to the
FileInfo class construc-
tor. The method returns an instance of the
FileStream class that you can use to read
from or write to the newly created file. For example, the following code uses the ...