[Serializable] |
In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all of the following are acceptable paths:
By default, full read/write access to new files is granted to all users.
| ctor #1 | Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path. |
| Attributes (inherited from System.IO.FileSystemInfo) |
Read-write See base class member description: System.IO.FileSystemInfo.Attributes Gets or sets the FileAttributes of the current FileSystemInfo. |
| CreationTime (inherited from System.IO.FileSystemInfo) |
Read-write See base class member description: System.IO.FileSystemInfo.CreationTime Gets or sets the creation time of the current FileSystemInfo object. |
| Directory | Read-only Gets an instance of the parent directory. |
| DirectoryName | Read-only Gets a string representing the directory's full path. |
| Exists | Read-only Overridden: Gets a value indicating whether a file exists. |
| Extension (inherited from System.IO.FileSystemInfo) |
Read-only See base class member description: System.IO.FileSystemInfo.Extension Gets the string representing the extension part of the file. |
| FullName (inherited from System.IO.FileSystemInfo) |
Read-only See base class member description: System.IO.FileSystemInfo.FullName Gets the full path of the directory or file. |
| LastAccessTime (inherited from System.IO.FileSystemInfo) |
Read-write See base class member description: System.IO.FileSystemInfo.LastAccessTime Gets or sets the time the current file or directory was last accessed. |
| LastWriteTime (inherited from System.IO.FileSystemInfo) |
Read-write See base class member description: System.IO.FileSystemInfo.LastWriteTime Gets or sets the time when the current file or directory was last written to. |
| Length | Read-only Gets the size of the current file or directory. |
| Name | Read-only Overridden: Gets the name of the file. |
| AppendText | Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo. |
| CopyTo | Overloaded:CopyTo(string destFileName) Copies an existing file to a new file, disallowing the overwriting of an existing file. |
| CopyTo | Overloaded:CopyTo(string destFileName, bool overwrite) Copies an existing file to a new file, allowing the overwriting of an existing file. |
| Create | Creates a file. |
| CreateObjRef (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. |
| CreateText | Creates a StreamWriter that writes a new text file. |
| Delete | Overridden: Permanently deletes a file. |
| Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
| GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
| GetLifetimeService (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. |
| GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
| InitializeLifetimeService (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. |
| MoveTo | Moves a specified file to a new location, providing the option to specify a new file name. |
| Open | Overloaded:Open(FileMode mode) Opens a file in the specified mode. |
| Open | Overloaded:Open(FileMode mode, FileAccess access) Opens a file in the specified mode with read, write, or read/write access. |
| Open | Overloaded:Open(FileMode mode, FileAccess access, FileShare share) Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. |
| OpenRead | Creates a read-only FileStream. |
| OpenText | Creates a StreamReader with UTF8 encoding that reads from an existing text file. |
| OpenWrite | Creates a write-only FileStream. |
| Refresh (inherited from System.IO.FileSystemInfo) |
See base class member description: System.IO.FileSystemInfo.Refresh Refreshes the state of the object. |
| ToString | Overridden: Returns the fully qualified path as a string. |
| FullPath (inherited from System.IO.FileSystemInfo) |
See base class member description: System.IO.FileSystemInfo.FullPath Represents the fully qualified path of the directory or file. |
| OriginalPath (inherited from System.IO.FileSystemInfo) |
See base class member description: System.IO.FileSystemInfo.OriginalPath The path originally specified by the user, whether relative or absolute. |
| Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
| MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public FileInfo( |
fileName
| Exception Type | Condition |
|---|---|
| ArgumentNullException | fileName is null. |
| SecurityException | The caller does not have the required permission. |
| ArgumentException | The file name is empty, contains only white spaces, or contains invalid characters. |
| UnauthorizedAccessException | Access to fileName is denied. |
| PathTooLongException | The specified path, file name, or both are too long. After full qualification, each must contain fewer than 256 characters. |
| NotSupportedException | fileName contains a colon (:) in the middle of the string. |
using System;
using System.IO;
public class FileInfoMainTest {
public static void Main() {
// either open an existing file, or create a new one
FileInfo fi = new FileInfo("temp.txt");
// create a writer, ready to add entries to the file
StreamWriter sw = fi.AppendText();
sw.WriteLine("This is a new entry to add to the file");
sw.WriteLine("This is yet another line to add...");
sw.Flush();
sw.Close();
// get the information out of the file, and print it to screen
StreamReader sr = new StreamReader( fi.OpenRead() );
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
protected string FullPath;
|
protected string OriginalPath;
|
public FileAttributes Attributes {get; set;}
|
| Exception Type | Condition |
|---|---|
| FileNotFoundException | The caller attempts to access a file that does not exist on disk. |
| SecurityException | The caller does not have the required permission. |
| ArgumentException | The caller attempts to set an invalid file attribute. |
| IOException | FileSystemInfo.Refresh cannot initialize the data. |
public DateTime CreationTime {get; set;}
|
| Exception Type | Condition |
|---|---|
| IOException | FileSystemInfo.Refresh cannot initialize the data. |
| FileNotFoundException | The FileSystemInfo object does not exist. |
public DirectoryInfo Directory {get;}
|
| Exception Type | Condition |
|---|---|
| DirectoryNotFoundException | The specified file does not exist. |
| SecurityException | The caller does not have the required permission. |
using System;
using System.IO;
public class DirectoryTest {
public static void Main() {
// open an existing file, or create a new one
FileInfo fi = new FileInfo("temp.txt");
// determine the full path of the file just created...
DirectoryInfo di = fi.Directory;
// figure out what other entries are in that directory
FileSystemInfo[] fsi = di.GetFileSystemInfos();
Console.WriteLine("The directory '{0}' contains the following files and directories:", di.FullName);
// print the names of all the files and subdirectories of that directory
foreach (FileSystemInfo info in fsi)
Console.WriteLine(info.Name);
}
}
public string DirectoryName {get;}
|
| Exception Type | Condition |
|---|---|
| SecurityException | The caller does not have the required permission. |
| ArgumentNullException | null was passed in for the directory name. |
string fileName = "C:\\autoexec.bat";
FileInfo fileInfo = new FileInfo(fileName);
if (!fileInfo.Exists) {
return;
}
Console.WriteLine("{0} has a directoryName of {1}",
fileName, fileInfo.DirectoryName);
public override bool Exists {get;}
|
using System;
using System.IO;
public class ExistsTest {
public static void Main() {
string neFile = "nonexistentfile";
// open an existing file, or create a new one
FileInfo fi = new FileInfo(neFile);
DetermineExists(fi, neFile);
neFile = "newFile.txt";
// create a file, so it exists
fi = new FileInfo(neFile);
FileStream fs = fi.Create();
DetermineExists(fi, neFile);
// close the file so it can be deleted
fs.Close();
// delete the file
try {
fi.Delete();
Console.WriteLine("The file '{0}' was deleted successfully", fi.Name);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private static void DetermineExists( FileInfo fi, string fileName ) {
// figure out if the file exists or not
if (fi.Exists)
Console.WriteLine("The file '{0}' exists in the specified directory", fileName);
else
Console.WriteLine("The file '{0}' does not exist in the specified directory", fileName);
}
}
public string Extension {get;}
|
public virtual string FullName {get;}
|
public DateTime LastAccessTime {get; set;}
|
| Exception Type | Condition |
|---|---|
| IOException | FileSystemInfo.Refresh cannot initialize the data. |
public DateTime LastWriteTime {get; set;}
|
| Exception Type | Condition |
|---|---|
| IOException | FileSystemInfo.Refresh cannot initialize the data. |
public long Length {get;}
|
| Exception Type | Condition |
|---|---|
| IOException | FileSystemInfo.Refresh cannot update the state of the file or directory. |
| FileNotFoundException | The file does not exist. |
string dirName = "C:\\";
DirectoryInfo dirInfo = new DirectoryInfo(dirName);
Console.WriteLine("{0} contains the following files:", dirName);
Console.WriteLine("Size\t Filename");
foreach (FileInfo fileInfo in dirInfo.GetFiles()) {
try {
Console.WriteLine("{0}\t {1}",
fileInfo.Length, fileInfo.Name);
}
catch (IOException e) {
Console.WriteLine("\t {0}: {1}", fileInfo.Name, e.Message);
}
}
public override string Name {get;}
|
using System;
using System.IO;
public class NameTest {
public static void Main() {
// create a reference to the current directory
DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory);
// create an array representing the files in the current directory
FileInfo[] fi = di.GetFiles();
Console.WriteLine("The following files exist in the current directory:");
// print out the names of those files
foreach (FileInfo fiTemp in fi)
Console.WriteLine(fiTemp.Name);
}
}
public StreamWriter AppendText(); |
using System;
using System.IO;
public class AppendTextTest {
public static void Main() {
// create a reference to a file, which may or may not exist
// if it doesn't exist, it is not yet created
FileInfo fi = new FileInfo("temp.txt");
// create a writer, ready to add entries to the file
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// get the information out of the file, and print it to screen,
// remember that the file may have other lines, if it already existed
StreamReader sr = new StreamReader( fi.OpenRead() );
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
destFileName
| Exception Type | Condition |
|---|---|
| ArgumentException | destFileName is empty, contains only white spaces, or contains invalid characters. |
| IOException | An error occurs, or the destination file already exists. |
| SecurityException | The caller does not have the required permission. |
| ArgumentNullException | destFileName is null. |
| UnauthorizedAccessException | A directory path is passed in, or the file is being moved to a different drive. |
| PathTooLongException | The specified path, file name, or both are too long. After full qualification, each must contain fewer than 256 characters. |
| NotSupportedException | destFileName contains a colon (:) in the middle of the string. |
using System;
using System.IO;
public class CopyToTest {
public static void Main() {
// create a reference to a file, which may or may not exist
// if it doesn't exist, it is not yet created
FileInfo fi = new FileInfo("temp.txt");
// create a writer, ready to add entries to the file
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// get the information out of the file, and print it to screen
StreamReader sr = new StreamReader( fi.OpenRead() );
Console.WriteLine("This is the information in the first file:");
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
// copy this file to ANOTHER file. The true parameter indicates
// to overwrite the file if it already exists
FileInfo newfi = fi.CopyTo("newTemp.txt", true);
// get the information out of the new file, and print it to screen
sr = new StreamReader( newfi.OpenRead() );
Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
destFileName
overwrite
| Exception Type | Condition |
|---|---|
| ArgumentException | destFileName is empty, contains only white spaces, or contains invalid characters. |
| IOException | An error occurs, or the destination file already exists and overwrite is false. |
| SecurityException | The caller does not have the required permission. |
| ArgumentNullException | destFileName is null. |
| UnauthorizedAccessException | A directory path is passed in, or the file is being moved to a different drive. |
| PathTooLongException | The specified path, file name, or both are too long. After full qualification, each must contain fewer than 256 characters. |
| NotSupportedException | destFileName contains a colon (:) in the middle of the string. |
public FileStream Create(); |
This method provides a convenient, instantiated wrapper for the functionality provided by File.Create.
requestedType
| Exception Type | Condition |
|---|---|
| RemotingException | This instance is not a valid remoting object. |
public StreamWriter CreateText(); |
| Exception Type | Condition |
|---|---|
| UnauthorizedAccessException | The file name is a directory. |
| IOException | The disk is read-only. |
| SecurityException | The caller does not have the required permission. |
FileInfo fileInfo = new FileInfo("myFile");
// Create the file and output some text to it.
StreamWriter s = fileInfo.CreateText();
s.WriteLine("Output to the file");
s.Close();
fileInfo.Refresh();
Console.WriteLine("File '{0}' now has size {1} bytes",
fileInfo.Name, fileInfo.Length);
public override void Delete(); |
| Exception Type | Condition |
|---|---|
| IOException | The target file is open or memory-mapped on a computer running Microsoft Windows NT. |
| SecurityException | The caller does not have the required permission. |
| UnauthorizedAccessException | The path is a directory. |
using System;
using System.IO;
public class DeleteTest {
public static void Main() {
// create a reference to a file
FileInfo fi = new FileInfo("temp.txt");
// actually create the file
FileStream fs = fi.Create();
// modify the file as required
// ...
// close the file
fs.Close();
// delete the file
fi.Delete();
}
}
~FileInfo(); |
public virtual int GetHashCode(); |
public object GetLifetimeService(); |
public Type GetType(); |
public virtual object InitializeLifetimeService(); |
public class MyClass : MarshalByRefObject
{
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
}
return lease;
}
}
protected object MemberwiseClone(); |
public void MoveTo( |
destFileName
| Exception Type | Condition |
|---|---|
| IOException | An I/O error occurs, such as the destination file already exists or the destination device is not ready. |
| ArgumentNullException | destFileName is null. |
| ArgumentException | destFileName is empty, contains only white spaces, or contains invalid characters. |
| SecurityException | The caller does not have the required permission. |
| UnauthorizedAccessException | destFileName is read-only or a directory. |
| FileNotFoundException | The file is not found. |
| DirectoryNotFoundException | The path specified in destFileName cannot be found. |
| PathTooLongException | The specified path, file name, or both are too long. After full qualification, each must contain fewer than 256 characters. |
| NotSupportedException | destFileName contains a colon (:) in the middle of the string. |
using System;
using System.IO;
public class MoveToTest {
public static void Main() {
// create a reference to a file, which may or may not exist
// if it doesn't exist, it is not yet created
FileInfo fi = new FileInfo("temp.txt");
// create a writer, ready to add entries to the file
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// ensure the target file doesn't exist, since this is disallowed...
if (File.Exists("newTemp.txt"))
File.Delete("newTemp.txt");
// move this file to ANOTHER file.
fi.MoveTo("newTemp.txt");
// get the information out of the new file, and print it to screen
StreamReader sr = new StreamReader( fi.OpenRead() );
Console.WriteLine("{0}This is the information in the new file, '{1}':", Environment.NewLine, fi.Name);
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
public FileStream Open( |
mode
| Exception Type | Condition |
|---|---|
| FileNotFoundException | The file is not found. |
| UnauthorizedAccessException | The file is read-only or a directory. |
| DirectoryNotFoundException | The directory is not found. |
| IOException | The file is already open. |
public FileStream Open( |
mode
access
| Exception Type | Condition |
|---|---|
| SecurityException | The caller does not have the required permission. |
| ArgumentException | path is empty or contains only white spaces. |
| FileNotFoundException | The file is not found. |
| ArgumentNullException | One or more arguments is null. |
| UnauthorizedAccessException | path is read-only or a directory. |
| DirectoryNotFoundException | The directory is not found. |
| IOException | The file is already open. |
public FileStream Open( |
mode
access
share
| Exception Type | Condition |
|---|---|
| SecurityException | The caller does not have the required permission. |
| ArgumentException | path is empty or contains only white spaces. |
| FileNotFoundException | The file is not found. |
| ArgumentNullException | One or more arguments is null. |
| UnauthorizedAccessException | path is read-only or a directory. |
| DirectoryNotFoundException | The directory is not found. |
| IOException | The file is already open. |
using System;
using System.IO;
public class OpenTest {
public static void Main() {
// open an existing file, or create a new one
FileInfo fi = new FileInfo("temp.txt");
// Open the file just specified. Open it so that no-one else can use it
FileStream fs = fi.Open( FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None );
// create another reference to the same file
FileInfo nextfi = new FileInfo("temp.txt");
try {
// try opening the same file, which is locked by the previous process
nextfi.Open( FileMode.OpenOrCreate, FileAccess.Read );
Console.WriteLine("The file was not locked, and was opened by a second process");
} catch (IOException) {
Console.WriteLine("The file could not be opened because it was locked by another process");
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
// close the file so it can be deleted
fs.Close();
}
}
public FileStream OpenRead(); |
| Exception Type | Condition |
|---|---|
| UnauthorizedAccessException | path is read-only or a directory. |
| DirectoryNotFoundException | The directory is not found. |
| IOException | The file is already open. |
// Create a temporary file.
string fileName = Path.GetTempFileName();
FileInfo fileInfo = new FileInfo(fileName);
// Write the current time to the file in binary form.
DateTime currentTime = DateTime.Now;
FileStream fileWriteStream = fileInfo.OpenWrite();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileWriteStream, currentTime);
fileWriteStream.Close();
// Read the time back from the file.
FileStream fileReadStream = fileInfo.OpenRead();
DateTime timeRead = (DateTime)binaryFormatter.Deserialize(fileReadStream);
fileReadStream.Close();
Console.WriteLine("Value written {0}", currentTime);
Console.WriteLine("Value read {0}", timeRead);
public StreamReader OpenText(); |
| Exception Type | Condition |
|---|---|
| SecurityException | The caller does not have the required permission. |
| FileNotFoundException | The file is not found. |
| UnauthorizedAccessException | path is read-only or a directory. |
| DirectoryNotFoundException | The directory is not found. |
string fileName = Path.GetTempFileName();
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine("File '{0}' created of size {1} bytes",
fileName, fileInfo.Length);
// Append some text to the file.
StreamWriter s = fileInfo.AppendText();
s.WriteLine("The text in the file");
s.Close();
fileInfo.Refresh();
Console.WriteLine("File '{0}' now has size {1} bytes",
fileName, fileInfo.Length);
// Read the text file
StreamReader r = fileInfo.OpenText();
string textLine;
while ((textLine = r.ReadLine()) != null) {
Console.WriteLine(textLine);
}
r.Close();
public FileStream OpenWrite(); |
| Exception Type | Condition |
|---|---|
| UnauthorizedAccessException | path is read-only or a directory. |
| DirectoryNotFoundException | The directory is not found. |
// Create a temporary file.
string fileName = Path.GetTempFileName();
FileInfo fileInfo = new FileInfo(fileName);
// Write the current time to the file in binary form.
DateTime currentTime = DateTime.Now;
FileStream fileWriteStream = fileInfo.OpenWrite();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileWriteStream, currentTime);
fileWriteStream.Close();
// Read the time back from the file.
FileStream fileReadStream = fileInfo.OpenRead();
DateTime timeRead = (DateTime)binaryFormatter.Deserialize(fileReadStream);
fileReadStream.Close();
Console.WriteLine("Value written {0}", currentTime);
Console.WriteLine("Value read {0}", timeRead);
public void Refresh(); |
| Exception Type | Condition |
|---|---|
| ArgumentException | The file is not found. |
| IOException | A device such as a disk drive is not ready. |
Calls must be made to Refresh before attempting to get the attribute information, or the information will be outdated.
public override string ToString(); |