System.IO.FileInfo Class

Assembly: Mscorlib.dll
Namespace: System.IO
Summary
Provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
C# Syntax:
[Serializable]
public sealed class FileInfo : FileSystemInfo
Remarks
All methods of the File class are static and can therefore be called without having an instance of a file. The FileInfo class contains only instance methods. The static methods of the File class perform security checks on all methods. If you are going to reuse an object several times, consider using the corresponding instance method of FileInfo instead, because the security check will not always be necessary.

Note In members that accept a path as an input string, that path must be well-formed or an exception is raised. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Therefore, the path is malformed and an exception is raised. Similarly, a path or a combination of paths cannot be fully qualified twice. For example, "c:\temp c:\windows" also raises an exception in most cases. Ensure that your paths are well-formed when using methods that accept a path string.

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.

See also:
System.IO Namespace

System.IO.FileInfo Member List:

Public Constructors
ctor #1 Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.
Public Properties
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.
Public Methods
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.
Protected Fields
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.
Protected Methods
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:


System.IO.FileInfo Member Details

ctor #1
Summary
Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.
C# Syntax:
public FileInfo(
   string fileName
);
Parameters:

fileName

The fully qualified name of the new file, or the relative file name.

Exceptions
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.
Remarks
You can specify either the fully qualified or the relative file name, but the security check gets the fully qualified name.
Example
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() );
    }
}

    
.NET Framework Security:
FileIOPermission for reading files. Associated enumeration: FileIOPermissionAccess.Read

Return to top


Field: FullPath
Inherited
See base class member description: System.IO.FileSystemInfo.FullPath

Summary
Represents the fully qualified path of the directory or file.
C# Syntax:
protected string FullPath;
Remarks


Notes to inheritors: Classes derived from FileSystemInfo can use the FullPath field to determine the full path of the object being manipulated.

Return to top


Field: OriginalPath
Inherited
See base class member description: System.IO.FileSystemInfo.OriginalPath

Summary
The path originally specified by the user, whether relative or absolute.
C# Syntax:
protected string OriginalPath;

Return to top


Property: Attributes (read-write)
Inherited
See base class member description: System.IO.FileSystemInfo.Attributes

Summary
Gets or sets the FileAttributes of the current FileSystemInfo.
C# Syntax:
public FileAttributes Attributes {get; set;}
Exceptions
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.
Remarks
The value of this property is a combination of the archive, compressed, directory, hidden, offline, read-only, system, and temporary file attribute flags.
.NET Framework Security:
FileIOPermissionAccess Write permission required to set the attributes for the specified file.

Return to top


Property: CreationTime (read-write)
Inherited
See base class member description: System.IO.FileSystemInfo.CreationTime

Summary
Gets or sets the creation time of the current FileSystemInfo object.
C# Syntax:
public DateTime CreationTime {get; set;}
Exceptions
Exception Type Condition
IOException FileSystemInfo.Refresh cannot initialize the data.
FileNotFoundException The FileSystemInfo object does not exist.
Remarks
This property value is null if the file system containing the FileSystemInfo object does not support this information.

Return to top


Property: Directory (read-only)
Summary
Gets an instance of the parent directory.
C# Syntax:
public DirectoryInfo Directory {get;}
Exceptions
Exception Type Condition
DirectoryNotFoundException The specified file does not exist.
SecurityException The caller does not have the required permission.
Remarks
To get the parent directory as a string, use the FileInfo.DirectoryName property.
Example
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);
    }
}

    
.NET Framework Security:
FileIOPermission for reading files. Associated enumeration: FileIOPermissionAccess.Read

Return to top


Property: DirectoryName (read-only)
Summary
Gets a string representing the directory's full path.
C# Syntax:
public string DirectoryName {get;}
Exceptions
Exception Type Condition
SecurityException The caller does not have the required permission.
ArgumentNullException null was passed in for the directory name.
Remarks
To get the parent directory as a DirectoryInfo object, use the FileInfo.Directory property.
Example
        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);

    
.NET Framework Security:
FileIOPermission for reading files. Associated enumeration: FileIOPermissionAccess.PathDiscovery

Return to top


Overridden Property: Exists (read-only)
Summary
Gets a value indicating whether a file exists.
C# Syntax:
public override bool Exists {get;}
Example
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);
    }
}

    

Return to top


Property: Extension (read-only)
Inherited
See base class member description: System.IO.FileSystemInfo.Extension

Summary
Gets the string representing the extension part of the file.
C# Syntax:
public string Extension {get;}
Remarks
The Extension property returns the FileSystemInfo extension, including the period (.). For example, for a file c:\NewFile.txt, this property returns ".txt".

Return to top


Property: FullName (read-only)
Inherited
See base class member description: System.IO.FileSystemInfo.FullName

Summary
Gets the full path of the directory or file.
C# Syntax:
public virtual string FullName {get;}
Remarks
For example, for a file c:\NewFile.txt, this property returns "NewFile.txt".
.NET Framework Security:
FileIOPermission for access to the path. Associated enumeration: FileIOPermissionAccess.PathDiscovery

Return to top


Property: LastAccessTime (read-write)
Inherited
See base class member description: System.IO.FileSystemInfo.LastAccessTime

Summary
Gets or sets the time the current file or directory was last accessed.
C# Syntax:
public DateTime LastAccessTime {get; set;}
Exceptions
Exception Type Condition
IOException FileSystemInfo.Refresh cannot initialize the data.
Remarks
This property value is null if the file system containing the file does not support this information.

Return to top


Property: LastWriteTime (read-write)
Inherited
See base class member description: System.IO.FileSystemInfo.LastWriteTime

Summary
Gets or sets the time when the current file or directory was last written to.
C# Syntax:
public DateTime LastWriteTime {get; set;}
Exceptions
Exception Type Condition
IOException FileSystemInfo.Refresh cannot initialize the data.
Remarks
This property value is null if the file system containing the file does not support this information.

Return to top


Property: Length (read-only)
Summary
Gets the size of the current file or directory.
C# Syntax:
public long Length {get;}
Exceptions
Exception Type Condition
IOException FileSystemInfo.Refresh cannot update the state of the file or directory.
FileNotFoundException The file does not exist.
Remarks
This property value is null if the file system containing the file does not support this information.
Example
        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);
            }
        }

    

Return to top


Overridden Property: Name (read-only)
Summary
Gets the name of the file.
C# Syntax:
public override string Name {get;}
Example
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);
    }
}

    

Return to top


Method: AppendText()
Summary
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
C# Syntax:
public StreamWriter AppendText();
Return Value:
A new StreamWriter.
Example
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() );
    }
}

    
.NET Framework Security:
FileIOPermission for reading and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Append
See also:
StreamWriter

Return to top


Overloaded Method: CopyTo(
   string destFileName
)
Summary
Copies an existing file to a new file, disallowing the overwriting of an existing file.
C# Syntax:
public FileInfo CopyTo(
   string destFileName
);
Parameters:

destFileName

The name of the new file to copy to.

Return Value:
A new file with a fully qualified path.
Exceptions
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.
Remarks
Use the CopyTo(String, Boolean) method to allow overwriting of an existing file.
Example
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() );
    }
}

    

.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write

Return to top


Overloaded Method: CopyTo(
   string destFileName,
   bool overwrite
)
Summary
Copies an existing file to a new file, allowing the overwriting of an existing file.
C# Syntax:
public FileInfo CopyTo(
   string destFileName,
   bool overwrite
);
Parameters:

destFileName

The name of the new file to copy to.

overwrite

true to allow an existing file to be overwritten; otherwise, false.

Return Value:
A new file, or an overwrite of an existing file if overwrite is true. If the file exists and overwrite is false, an IOException is thrown.
Exceptions
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.
Remarks
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo(String) method to prevent overwriting of an existing file by default.
.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write

Return to top


Method: Create()
Summary
Creates a file.
C# Syntax:
public FileStream Create();
Return Value:
A new file.
Remarks
By default, full read/write access to new files is granted to all users.

This method provides a convenient, instantiated wrapper for the functionality provided by File.Create.

.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Method: CreateText()
Summary
Creates a StreamWriter that writes a new text file.
C# Syntax:
public StreamWriter CreateText();
Return Value:
A new StreamWriter.
Exceptions
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.
Remarks
By default, full read/write access to new files is granted to all users.
Example
        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);

    
.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write
See also:
StreamWriter

Return to top


Overridden Method: Delete()
Summary
Permanently deletes a file.
C# Syntax:
public override void Delete();
Exceptions
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.
Remarks
If the file does not exist, this method does nothing.
Example
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();
    }
}

    
.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumeration: FileIOPermissionAccess.Write

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~FileInfo();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.InitializeLifetimeService

Summary
Obtains a lifetime service object to control the lifetime policy for this instance.
C# Syntax:
public virtual object InitializeLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.
Remarks
For more information about lifetime services, see the LifetimeServices class.
Example
The following code example demonstrates creating a lease.
 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;
   }
 }

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: MoveTo(
   string destFileName
)
Summary
Moves a specified file to a new location, providing the option to specify a new file name.
C# Syntax:
public void MoveTo(
   string destFileName
);
Parameters:

destFileName

The path to move the file to, which can specify a different file name.

Exceptions
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.
Remarks
This method works across disk volumes. For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.
Example
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() );
    }
}

    
.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write

Return to top


Overloaded Method: Open(
   FileMode mode
)
Summary
Opens a file in the specified mode.
C# Syntax:
public FileStream Open(
   FileMode mode
);
Parameters:

mode

A FileMode constant specifying the mode (for example, Open or Append) in which to open the file.

Return Value:
A file opened in the specified mode, with read/write access and unshared.
Exceptions
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.
.NET Framework Security:
FileIOPermission for writing to and reading from files. Associated enumerations: FileIOPermissionAccess.Write and FileIOPermissionAccess.Read

Return to top


Overloaded Method: Open(
   FileMode mode,
   FileAccess access
)
Summary
Opens a file in the specified mode with read, write, or read/write access.
C# Syntax:
public FileStream Open(
   FileMode mode,
   FileAccess access
);
Parameters:

mode

A FileMode constant specifying the mode (for example, Open or Append) in which to open the file.

access

A FileAccess constant specifying whether to open the file with Read, Write, or ReadWrite file access.

Return Value:
A FileStream object opened in the specified mode and access, and unshared.
Exceptions
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.
.NET Framework Security:
FileIOPermission for writing to and reading from files. Associated enumerations: FileIOPermissionAccess.Write and FileIOPermissionAccess.Read

Return to top


Overloaded Method: Open(
   FileMode mode,
   FileAccess access,
   FileShare share
)
Summary
Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.
C# Syntax:
public FileStream Open(
   FileMode mode,
   FileAccess access,
   FileShare share
);
Parameters:

mode

A FileMode constant specifying the mode (for example, Open or Append) in which to open the file.

access

A FileAccess constant specifying whether to open the file with Read, Write, or ReadWrite file access.

share

A FileShare constant specifying the type of access other FileStream objects have to this file.

Return Value:
A FileStream object opened with the specified mode, access, and sharing options.
Exceptions
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.
Example
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();
    }
}

    
.NET Framework Security:
FileIOPermission for writing to and reading from files. Associated enumerations: FileIOPermissionAccess.Write and FileIOPermissionAccess.Read

Return to top


Method: OpenRead()
Summary
Creates a read-only FileStream.
C# Syntax:
public FileStream OpenRead();
Return Value:
A new read-only FileStream object.
Exceptions
Exception Type Condition
UnauthorizedAccessException path is read-only or a directory.
DirectoryNotFoundException The directory is not found.
IOException The file is already open.
Example

        // 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);

    
.NET Framework Security:
FileIOPermission for reading files. Associated enumeration: FileIOPermissionAccess.Read

Return to top


Method: OpenText()
Summary
Creates a StreamReader with UTF8 encoding that reads from an existing text file.
C# Syntax:
public StreamReader OpenText();
Return Value:
A new StreamReader with UTF8 encoding.
Exceptions
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.
Example
        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();

    
.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write
See also:
Encoding.UTF8 | StreamReader

Return to top


Method: OpenWrite()
Summary
Creates a write-only FileStream.
C# Syntax:
public FileStream OpenWrite();
Return Value:
A new write-only unshared FileStream object.
Exceptions
Exception Type Condition
UnauthorizedAccessException path is read-only or a directory.
DirectoryNotFoundException The directory is not found.
Example

        // 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);

    
.NET Framework Security:
FileIOPermission for reading and writing files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write

Return to top


Method: Refresh()
Inherited
See base class member description: System.IO.FileSystemInfo.Refresh

Summary
Refreshes the state of the object.
C# Syntax:
public void Refresh();
Exceptions
Exception Type Condition
ArgumentException The file is not found.
IOException A device such as a disk drive is not ready.
Remarks
FileSystemInfo.Refresh takes a snapshot of the file from the current file system.Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information. This can happen on platforms such as Windows 98.

Calls must be made to Refresh before attempting to get the attribute information, or the information will be outdated.

Return to top


Overridden Method: ToString()
Summary
Returns the fully qualified path as a string.
C# Syntax:
public override string ToString();
Return Value:
A string representing the fully qualified path.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.