แก้ไข

แชร์ผ่าน


File.Create Method

Definition

Creates, or truncates and overwrites, a file in the specified path.

Overloads

Create(String)

Creates, or truncates and overwrites, a file in the specified path.

Create(String, Int32)

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

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, 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)

Source:
File.cs
Source:
File.cs
Source:
File.cs

Creates, or truncates and 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

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.

path is null.

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());
        }
    }
}
open System.IO
open System.Text

let path = @"c:\temp\MyTest.txt"

// Create the file, or overwrite if the file exists.
do
    use fs = File.Create path

    let info =
        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.
do
    use sr = File.OpenText path
    let mutable s = sr.ReadLine()

    while isNull s |> not do
        printfn $"{s}"
        s <- sr.ReadLine()
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 deleted and 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

Applies to

Create(String, Int32)

Source:
File.cs
Source:
File.cs
Source:
File.cs

Creates, or truncates and 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

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.

path is null.

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);
            }
        }
    }
}
open System.IO
open System.Text

let path = @"c:\temp\MyTest.txt"

// Create the file, or overwrite if the file exists.
do
    use fs = File.Create(path, 1024)

    let info =
        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.
do
    use sr = File.OpenText path
    let mutable s = sr.ReadLine()

    while isNull s |> not do
        printfn $"{s}"
        s <- sr.ReadLine()
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 replaced.

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

Applies to

Create(String, Int32, FileOptions)

Source:
File.cs
Source:
File.cs
Source:
File.cs

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.

options
FileOptions

One of the FileOptions values that describes how to create or overwrite the file.

Returns

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.

path is null.

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 replaced.

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, 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.

options
FileOptions

One of the FileOptions values that describes how to create or overwrite the file.

fileSecurity
FileSecurity

A FileSecurity object that determines the access control and audit security for the file.

Returns

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.

path is null.

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 replaced.

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.

Important

This method was ported to .NET Core 3.1 in the following form: Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity).

Applies to