When a file is opened in this mode, any of the file’s existing contents will be overwritten.

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

File.Create Method

  • Reference

Definition

Creates or overwrites a file in the specified path.

In this article

Overloads

Create(String, Int32, FileOptions, FileSecurity)

Creates or overwrites a file in the specified path, specifying a buffer size, options that describe how to create or overwrite the file, and a value that determines the access control and audit security for the file.

Create(String, Int32, FileOptions)

Creates or overwrites a file in the specified path, specifying a buffer size and options that describe how to create or overwrite the file.

Create(String)

Creates or overwrites a file in the specified path.

Create(String, Int32)

Creates or overwrites a file in the specified path, specifying a buffer size.

Create(String, Int32, FileOptions, FileSecurity)

Creates or overwrites a file in the specified path, specifying a buffer size, options that describe how to create or overwrite the file, and a value that determines the access control and audit security for the file.

public:
 static System::IO::FileStream ^ Create(System::String ^ path, int bufferSize, System::IO::FileOptions options, System::Security::AccessControl::FileSecurity ^ fileSecurity);
public static System.IO.FileStream Create (string path, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity);
static member Create : string * int * System.IO.FileOptions * System.Security.AccessControl.FileSecurity -> System.IO.FileStream
Public Shared Function Create (path As String, bufferSize As Integer, options As FileOptions, fileSecurity As FileSecurity) As FileStream

Parameters

path String

The path and name of the file to create.

bufferSize Int32

The number of bytes buffered for reads and writes to the file.

Returns

FileStream

A new file with the specified buffer size, file options, and file security.

Exceptions

The caller does not have the required permission.

-or-

path specified a file that is read-only.

-or-

path specified a file that is hidden.

.NET Framework and .NET Core versions older than 2.1: path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the GetInvalidPathChars() method.

The specified path, file name, or both exceed the system-defined maximum length.

The specified path is invalid (for example, it is on an unmapped drive).

An I/O error occurred while creating the file.

path is in an invalid format.

Remarks

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare, Int32) constructor overload. If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.

By default, full read/write access to new files is granted to all users. The file is opened with read/write access and must be closed before it can be opened by another application.

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

Applies to

Create(String, Int32, FileOptions)

Creates or overwrites a file in the specified path, specifying a buffer size and options that describe how to create or overwrite the file.

public:
 static System::IO::FileStream ^ Create(System::String ^ path, int bufferSize, System::IO::FileOptions options);
public static System.IO.FileStream Create (string path, int bufferSize, System.IO.FileOptions options);
static member Create : string * int * System.IO.FileOptions -> System.IO.FileStream
Public Shared Function Create (path As String, bufferSize As Integer, options As FileOptions) As FileStream

Parameters

path String

The path and name of the file to create.

bufferSize Int32

The number of bytes buffered for reads and writes to the file.

Returns

FileStream

A new file with the specified buffer size.

Exceptions

The caller does not have the required permission.

-or-

path specified a file that is read-only.

-or-

path specified a file that is hidden.

.NET Framework and .NET Core versions older than 2.1: path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the GetInvalidPathChars() method.

The specified path, file name, or both exceed the system-defined maximum length.

The specified path is invalid (for example, it is on an unmapped drive.

An I/O error occurred while creating the file.

path is in an invalid format.

Remarks

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare, Int32) constructor overload. If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.

By default, full read/write access to new files is granted to all users. The file is opened with read/write access and must be closed before it can be opened by another application.

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

Applies to

Create(String)

Creates or overwrites a file in the specified path.

public:
 static System::IO::FileStream ^ Create(System::String ^ path);
public static System.IO.FileStream Create (string path);
static member Create : string -> System.IO.FileStream
Public Shared Function Create (path As String) As FileStream

Parameters

path String

The path and name of the file to create.

Returns

FileStream

A FileStream that provides read/write access to the file specified in path.

Exceptions

The caller does not have the required permission.

-or-

path specified a file that is read-only.

-or-

path specified a file that is hidden.

.NET Framework and .NET Core versions older than 2.1: path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the GetInvalidPathChars() method.

The specified path, file name, or both exceed the system-defined maximum length.

The specified path is invalid (for example, it is on an unmapped drive).

An I/O error occurred while creating the file.

path is in an invalid format.

Examples

The following example creates a file in the specified path, writes some information to the file, and reads from the file.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Create the file, or overwrite if the file exists.
   FileStream^ fs = File::Create( path );
   try
   {
      array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." );
      
      // Add some information to the file.
      fs->Write( info, 0, info->Length );
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }

   // Open the stream and read it back.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
            delete (IDisposable^)sr;
   }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        try
        {
            // Create the file, or overwrite if the file exists.
            using (FileStream fs = File.Create(path))
            {
                byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }

            // Open the stream and read it back.
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt"

    Try
      ' Create the file, or overwrite if the file exists.
      Using fs As FileStream = File.Create(path)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")

        ' Add some information to the file.
        fs.Write(info, 0, info.Length)
      End Using

      ' Open the stream and read it back. 
      Using sr As StreamReader = File.OpenText(path)
        Do While sr.Peek() >= 0
          Console.WriteLine(sr.ReadLine())
        Loop
      End Using

    Catch ex As Exception
      Console.WriteLine(ex.ToString())
    End Try

  End Sub
End Class

Remarks

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

This method is equivalent to the Create(String, Int32) method overload using the default buffer size of 4,096 bytes.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.

By default, full read/write access to new files is granted to all users. The file is opened with read/write access and must be closed before it can be opened by another application.

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

See also

  • File and Stream I/O
  • Reading Text From A File
  • How to: Write Text to a File
  • How to: Read and Write to a Newly Created Data File

Applies to

Create(String, Int32)

Creates or overwrites a file in the specified path, specifying a buffer size.

public:
 static System::IO::FileStream ^ Create(System::String ^ path, int bufferSize);
public static System.IO.FileStream Create (string path, int bufferSize);
static member Create : string * int -> System.IO.FileStream
Public Shared Function Create (path As String, bufferSize As Integer) As FileStream

Parameters

path String

The path and name of the file to create.

bufferSize Int32

The number of bytes buffered for reads and writes to the file.

Returns

FileStream

A FileStream with the specified buffer size that provides read/write access to the file specified in path.

Exceptions

The caller does not have the required permission.

-or-

path specified a file that is read-only.

-or-

path specified a file that is hidden.

.NET Framework and .NET Core versions older than 2.1: path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the GetInvalidPathChars() method.

The specified path, file name, or both exceed the system-defined maximum length.

The specified path is invalid (for example, it is on an unmapped drive).

An I/O error occurred while creating the file.

path is in an invalid format.

Examples

The following example creates a file with the specified buffer size.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Create the file, or overwrite if the file exists.
   FileStream^ fs = File::Create( path, 1024 );
   try
   {
      array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." );
      
      // Add some information to the file.
      fs->Write( info, 0, info->Length );
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }

   // Open the stream and read it back.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
            delete (IDisposable^)sr;
   }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Create the file, or overwrite if the file exists.
        using (FileStream fs = File.Create(path, 1024))
        {
            byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt"

    Try
      ' Create the file, or overwrite if the file exists.
      Using fs As FileStream = File.Create(path, 1024)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")

        ' Add some information to the file.
        fs.Write(info, 0, info.Length)
      End Using

      ' Open the stream and read it back. 
      Using sr As StreamReader = File.OpenText(path)
        Do While sr.Peek() >= 0
          Console.WriteLine(sr.ReadLine())
        Loop
      End Using

    Catch ex As Exception
      Console.WriteLine(ex.ToString())
    End Try

  End Sub
End Class

Remarks

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare, Int32) constructor overload. If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.

By default, full read/write access to new files is granted to all users. The file is opened with read/write access and must be closed before it can be opened by another application.

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

See also

  • File and Stream I/O
  • Reading Text From A File
  • How to: Write Text to a File
  • How to: Read and Write to a Newly Created Data File

Applies to

When a file that already exists is opened in append mode the file's existing contents are not erased?

If an existing file is opened in append mode, what happens to the file's existing contents? It will not be erased and new data will be written at the end of the file's current contents.

When you open a file that file already exists on the disk using the W mode?

Terms in this set (9) When working with a sequential access file, you can jump directly to any piece of data in the file without reading the data that comes before it. When you open a file that file already exists on the disk using the "w" mode, the contents of the existing file will be erased.

What happens if you try to open a file for input read mode but that file does not exist?

When you open a file for reading, if the file does not exist, the program will open an empty file.

What will happen when a program opens a file in write mode if the file doesn't exist?

If you open a file for reading and the file doesn't exist, then an exception is thrown. If you open a file for writing and the file doesn't exist, then the file is created with 0 length.