Skip to main content
File Class
 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.

To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)


[ComVisibleAttribute(true)]
public static class File
[ComVisibleAttribute(true)]
public ref class File abstract sealed 
[<AbstractClass>]
[<Sealed>]
[<ComVisibleAttribute(true)>]
type File = class end
<ComVisibleAttribute(True)>
Public NotInheritable Class File
NameDescription
System_CAPS_pubmethod System_CAPS_static AppendAllLines

Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static AppendAllLines

Appends lines to a file by using a specified encoding, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static AppendAllText

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

System_CAPS_pubmethod System_CAPS_static AppendAllText

Appends the specified string to the file, creating the file if it does not already exist.

System_CAPS_pubmethod System_CAPS_static AppendText

Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.

System_CAPS_pubmethod System_CAPS_static Copy

Copies an existing file to a new file. Overwriting a file of the same name is not allowed.

System_CAPS_pubmethod System_CAPS_static Copy

Copies an existing file to a new file. Overwriting a file of the same name is allowed.

System_CAPS_pubmethod System_CAPS_static Create

Creates or overwrites a file in the specified path.

System_CAPS_pubmethod System_CAPS_static Create

Creates or overwrites the specified file.

System_CAPS_pubmethod System_CAPS_static Create

Creates or overwrites the specified file, specifying a buffer size and a FileOptions value that describes how to create or overwrite the file.

System_CAPS_pubmethod System_CAPS_static Create

Creates or overwrites the specified file with the specified buffer size, file options, and file security.

System_CAPS_pubmethod System_CAPS_static CreateText

Creates or opens a file for writing UTF-8 encoded text.

System_CAPS_pubmethod System_CAPS_static Decrypt

Decrypts a file that was encrypted by the current account using the Encrypt method.

System_CAPS_pubmethod System_CAPS_static Delete

Deletes the specified file.

System_CAPS_pubmethod System_CAPS_static Encrypt

Encrypts a file so that only the account used to encrypt the file can decrypt it.

System_CAPS_pubmethod System_CAPS_static Exists

Determines whether the specified file exists.

System_CAPS_pubmethod System_CAPS_static GetAccessControl

Gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.

System_CAPS_pubmethod System_CAPS_static GetAccessControl

Gets a FileSecurity object that encapsulates the specified type of access control list (ACL) entries for a particular file.

System_CAPS_pubmethod System_CAPS_static GetAttributes

Gets the FileAttributes of the file on the path.

System_CAPS_pubmethod System_CAPS_static GetCreationTime

Returns the creation date and time of the specified file or directory.

System_CAPS_pubmethod System_CAPS_static GetCreationTimeUtc

Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.

System_CAPS_pubmethod System_CAPS_static GetLastAccessTime

Returns the date and time the specified file or directory was last accessed.

System_CAPS_pubmethod System_CAPS_static GetLastAccessTimeUtc

Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.

System_CAPS_pubmethod System_CAPS_static GetLastWriteTime

Returns the date and time the specified file or directory was last written to.

System_CAPS_pubmethod System_CAPS_static GetLastWriteTimeUtc

Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.

System_CAPS_pubmethod System_CAPS_static Move

Moves a specified file to a new location, providing the option to specify a new file name.

System_CAPS_pubmethod System_CAPS_static Open

Opens a FileStream on the specified path with read/write access.

System_CAPS_pubmethod System_CAPS_static Open

Opens a FileStream on the specified path, with the specified mode and access.

System_CAPS_pubmethod System_CAPS_static Open

Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

System_CAPS_pubmethod System_CAPS_static OpenRead

Opens an existing file for reading.

System_CAPS_pubmethod System_CAPS_static OpenText

Opens an existing UTF-8 encoded text file for reading.

System_CAPS_pubmethod System_CAPS_static OpenWrite

Opens an existing file or creates a new file for writing.

System_CAPS_pubmethod System_CAPS_static ReadAllBytes

Opens a binary file, reads the contents of the file into a byte array, and then closes the file.

System_CAPS_pubmethod System_CAPS_static ReadAllLines

Opens a text file, reads all lines of the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static ReadAllLines

Opens a file, reads all lines of the file with the specified encoding, and then closes the file.

System_CAPS_pubmethod System_CAPS_static ReadAllText

Opens a text file, reads all lines of the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static ReadAllText

Opens a file, reads all lines of the file with the specified encoding, and then closes the file.

System_CAPS_pubmethod System_CAPS_static ReadLines

Reads the lines of a file.

System_CAPS_pubmethod System_CAPS_static ReadLines

Read the lines of a file that has a specified encoding.

System_CAPS_pubmethod System_CAPS_static Replace

Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.

System_CAPS_pubmethod System_CAPS_static Replace

Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors.

System_CAPS_pubmethod System_CAPS_static SetAccessControl

Applies access control list (ACL) entries described by a FileSecurity object to the specified file.

System_CAPS_pubmethod System_CAPS_static SetAttributes

Sets the specified FileAttributes of the file on the specified path.

System_CAPS_pubmethod System_CAPS_static SetCreationTime

Sets the date and time the file was created.

System_CAPS_pubmethod System_CAPS_static SetCreationTimeUtc

Sets the date and time, in coordinated universal time (UTC), that the file was created.

System_CAPS_pubmethod System_CAPS_static SetLastAccessTime

Sets the date and time the specified file was last accessed.

System_CAPS_pubmethod System_CAPS_static SetLastAccessTimeUtc

Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.

System_CAPS_pubmethod System_CAPS_static SetLastWriteTime

Sets the date and time that the specified file was last written to.

System_CAPS_pubmethod System_CAPS_static SetLastWriteTimeUtc

Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.

System_CAPS_pubmethod System_CAPS_static WriteAllBytes

Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

System_CAPS_pubmethod System_CAPS_static WriteAllLines

Creates a new file, writes a collection of strings to the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static WriteAllLines

Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static WriteAllLines

Creates a new file, write the specified string array to the file, and then closes the file.

System_CAPS_pubmethod System_CAPS_static WriteAllLines

Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.

System_CAPS_pubmethod System_CAPS_static WriteAllText

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

System_CAPS_pubmethod System_CAPS_static WriteAllText

Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.

System_CAPS_noteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Use the File class for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to a single file at a time. You can also use the File class to get and set file attributes or DateTime information related to the creation, access, and writing of a file. If you want to perform operations on multiple files, see DirectoryGetFiles or DirectoryInfoGetFiles.

Many of the File methods return other I/O types when you create or open files. You can use these other types to further manipulate a file. For more information, see specific File members such as OpenText, CreateText, or Create.

Because all File methods are static, it might be more efficient to use a File method rather than a corresponding FileInfo instance method if you want to perform only one action. All File methods require the path to the file that you are manipulating.

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.

By default, full read/write access to new files is granted to all users.

The following table describes the enumerations that are used to customize the behavior of various File methods.

Enumeration

Description

FileAccess

Specifies read and write access to a file.

FileShare

Specifies the level of access permitted for a file that is already in use.

FileMode

Specifies whether the contents of an existing file are preserved or overwritten, and whether requests to create an existing file cause an exception.

System_CAPS_noteNote

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 the following are acceptable paths:

  • "c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • "c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

  • "MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

  • "\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

For a list of common I/O tasks, see Common I-O Tasks.

The following example demonstrates how to use the File class to check whether a file exists, and depending on the result, either create a new file and write to it, or open the existing file and read from it. Before running the code, create a c:\temp folder.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        If File.Exists(path) = False Then
            ' Create a file to write to.
            Using sw As StreamWriter = File.CreateText(path)
                sw.WriteLine("Hello")
                sw.WriteLine("And")
                sw.WriteLine("Welcome")
                sw.Flush()
           End Using
        End If

        ' Open the file to read from.
        Using sr As StreamReader = File.OpenText(path)
            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
        End Using
    End Sub
End Class
using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   if (  !File::Exists( path ) )
   {

      // Create a file to write to.
      StreamWriter^ sw = File::CreateText( path );
      try
      {
         sw->WriteLine( "Hello" );
         sw->WriteLine( "And" );
         sw->WriteLine( "Welcome" );
      }
      finally
      {
         if ( sw )
                  delete (IDisposable^)(sw);
      }
   }

   // Open the file to read from.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
            delete (IDisposable^)(sr);
   }

   try
   {
      String^ path2 = String::Concat( path, "temp" );

      // Ensure that the target does not exist.
      File::Delete( path2 );

      // Copy the file.
      File::Copy( path, path2 );
      Console::WriteLine( "{0} was copied to {1}.", path, path2 );

      // Delete the newly created file.
      File::Delete( path2 );
      Console::WriteLine( "{0} was successfully deleted.", path2 );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top