File.Create Método
Definição
Cria ou substitui um arquivo no caminho especificado.Creates or overwrites a file in the specified path.
Sobrecargas
Create(String) |
Cria ou substitui um arquivo no caminho especificado.Creates or overwrites a file in the specified path. |
Create(String, Int32) |
Cria ou substitui um arquivo no caminho especificado usando o tamanho do buffer.Creates or overwrites a file in the specified path, specifying a buffer size. |
Create(String, Int32, FileOptions) |
Cria ou substitui um arquivo no caminho especificado usando o tamanho do buffer e opções que descrevem como criar ou substituir o arquivo.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) |
Cria ou substitui um arquivo no caminho especificado usando o tamanho do buffer, opções que descrevem como criar ou substituir o arquivo e um valor que determina o controle de acesso e a segurança de auditoria para o arquivo.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)
Cria ou substitui um arquivo no caminho especificado.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
Parâmetros
- path
- String
O caminho e o nome do arquivo a ser criado.The path and name of the file to create.
Retornos
Um FileStream que fornece acesso de leitura/gravação para o arquivo especificado em path
.A FileStream that provides read/write access to the file specified in path
.
Exceções
O chamador não tem a permissão necessária.The caller does not have the required permission.
- ou --or-
path
especificou um arquivo somente leitura.path
specified a file that is read-only.
- ou --or-
path
especificou um arquivo que está oculto.path
specified a file that is hidden.
path
é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos, conforme definido por InvalidPathChars.path
is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path
é null
.path
is null
.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).
Ocorreu um erro de E/S ao criar o arquivo.An I/O error occurred while creating the file.
path
está em um formato inválido.path
is in an invalid format.
Exemplos
O exemplo a seguir cria um arquivo no caminho especificado, grava algumas informações no arquivo e lê o arquivo.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
Comentários
O objeto FileStream criado por esse método tem um valor de FileShare padrão de None; nenhum outro processo ou código pode acessar o arquivo criado até que o identificador do arquivo original seja fechado.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.
Esse método é equivalente à sobrecarga do método de Create(String, Int32) usando o tamanho de buffer padrão de 4.096 bytes.This method is equivalent to the Create(String, Int32) method overload using the default buffer size of 4,096 bytes.
O parâmetro path
é permitido para especificar informações de caminho relativo ou absoluto.The path
parameter is permitted to specify relative or absolute path information. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.To obtain the current working directory, see GetCurrentDirectory.
Se o arquivo especificado não existir, ele será criado; Se ele existir e não for somente leitura, o conteúdo será substituído.If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.
Por padrão, o acesso completo de leitura/gravação para novos arquivos é concedido a todos os usuários.By default, full read/write access to new files is granted to all users. O arquivo é aberto com acesso de leitura/gravação e deve ser fechado para que possa ser aberto por outro aplicativo.The file is opened with read/write access and must be closed before it can be opened by another application.
Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.
Segurança
FileIOPermission
para obter permissão para ler e gravar no arquivo descrito pelo parâmetro path
.for permission to read and write to the file described by the path
parameter. Ação de segurança: Demand.Security action: Demand. Enumerações associadas: Read, WriteAssociated enumerations: Read, Write
Veja também
Create(String, Int32)
Cria ou substitui um arquivo no caminho especificado usando o tamanho do buffer.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
Parâmetros
- path
- String
O caminho e o nome do arquivo a ser criado.The path and name of the file to create.
- bufferSize
- Int32
O número de bytes armazenados em buffer para leituras e gravações no arquivo.The number of bytes buffered for reads and writes to the file.
Retornos
Um FileStream com o tamanho do buffer especificado que fornece acesso de leitura/gravação para o arquivo especificado em path
.A FileStream with the specified buffer size that provides read/write access to the file specified in path
.
Exceções
O chamador não tem a permissão necessária.The caller does not have the required permission.
- ou --or-
path
especificou um arquivo somente leitura.path
specified a file that is read-only.
- ou --or-
path
especificou um arquivo que está oculto.path
specified a file that is hidden.
path
é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos, conforme definido por InvalidPathChars.path
is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path
é null
.path
is null
.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).
Ocorreu um erro de E/S ao criar o arquivo.An I/O error occurred while creating the file.
path
está em um formato inválido.path
is in an invalid format.
Exemplos
O exemplo a seguir cria um arquivo com o tamanho de buffer especificado.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
Comentários
O objeto FileStream criado por esse método tem um valor de FileShare padrão de None; nenhum outro processo ou código pode acessar o arquivo criado até que o identificador do arquivo original seja fechado.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.
O parâmetro path
é permitido para especificar informações de caminho relativo ou absoluto.The path
parameter is permitted to specify relative or absolute path information. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.To obtain the current working directory, see GetCurrentDirectory.
Esse método é equivalente à sobrecarga do construtor de FileStream(String, FileMode, FileAccess, FileShare, Int32).This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare, Int32) constructor overload. Se o arquivo especificado não existir, ele será criado; Se ele existir e não for somente leitura, o conteúdo será substituído.If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.
Por padrão, o acesso completo de leitura/gravação para novos arquivos é concedido a todos os usuários.By default, full read/write access to new files is granted to all users. O arquivo é aberto com acesso de leitura/gravação e deve ser fechado para que possa ser aberto por outro aplicativo.The file is opened with read/write access and must be closed before it can be opened by another application.
Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.
Segurança
FileIOPermission
para obter permissão para ler e gravar no arquivo descrito pelo parâmetro path
.for permission to read and write to the file described by the path
parameter. Ação de segurança: Solicitar.Security action: Demand. Enumerações associadas: Read, WriteAssociated enumerations: Read, Write
Veja também
Create(String, Int32, FileOptions)
Cria ou substitui um arquivo no caminho especificado usando o tamanho do buffer e opções que descrevem como criar ou substituir o arquivo.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
Parâmetros
- path
- String
O caminho e o nome do arquivo a ser criado.The path and name of the file to create.
- bufferSize
- Int32
O número de bytes armazenados em buffer para leituras e gravações no arquivo.The number of bytes buffered for reads and writes to the file.
- options
- FileOptions
Um dos valores de FileOptions que descreve como criar ou substituir o arquivo.One of the FileOptions values that describes how to create or overwrite the file.
Retornos
Um novo arquivo com o tamanho do buffer especificado.A new file with the specified buffer size.
Exceções
O chamador não tem a permissão necessária.The caller does not have the required permission.
- ou --or-
path
especificou um arquivo somente leitura.path
specified a file that is read-only.
- ou --or-
path
especificou um arquivo que está oculto.path
specified a file that is hidden.
path
é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos, conforme definido por InvalidPathChars.path
is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path
é null
.path
is null
.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive.
Ocorreu um erro de E/S ao criar o arquivo.An I/O error occurred while creating the file.
path
está em um formato inválido.path
is in an invalid format.
Comentários
O parâmetro path
é permitido para especificar informações de caminho relativo ou absoluto.The path
parameter is permitted to specify relative or absolute path information. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.To obtain the current working directory, see GetCurrentDirectory.
Esse método é equivalente à sobrecarga do construtor de FileStream(String, FileMode, FileAccess, FileShare, Int32).This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare, Int32) constructor overload. Se o arquivo especificado não existir, ele será criado; Se ele existir e não for somente leitura, o conteúdo será substituído.If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.
Por padrão, o acesso completo de leitura/gravação para novos arquivos é concedido a todos os usuários.By default, full read/write access to new files is granted to all users. O arquivo é aberto com acesso de leitura/gravação e deve ser fechado para que possa ser aberto por outro aplicativo.The file is opened with read/write access and must be closed before it can be opened by another application.
Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.
Segurança
FileIOPermission
para obter permissão para ler e gravar no arquivo descrito pelo parâmetro path
.for permission to read and write to the file described by the path
parameter. Ação de segurança: Solicitar.Security action: Demand. Enumerações associadas: Read, WriteAssociated enumerations: Read, Write
Create(String, Int32, FileOptions, FileSecurity)
Cria ou substitui um arquivo no caminho especificado usando o tamanho do buffer, opções que descrevem como criar ou substituir o arquivo e um valor que determina o controle de acesso e a segurança de auditoria para o arquivo.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
Parâmetros
- path
- String
O caminho e o nome do arquivo a ser criado.The path and name of the file to create.
- bufferSize
- Int32
O número de bytes armazenados em buffer para leituras e gravações no arquivo.The number of bytes buffered for reads and writes to the file.
- options
- FileOptions
Um dos valores de FileOptions que descreve como criar ou substituir o arquivo.One of the FileOptions values that describes how to create or overwrite the file.
- fileSecurity
- FileSecurity
Um objeto FileSecurity que determina o controle de acesso e a segurança de auditoria para o arquivo.A FileSecurity object that determines the access control and audit security for the file.
Retornos
Um novo arquivo com o tamanho do buffer, as opções de arquivo e a segurança de arquivo especificados.A new file with the specified buffer size, file options, and file security.
Exceções
O chamador não tem a permissão necessária.The caller does not have the required permission.
- ou --or-
path
especificou um arquivo somente leitura.path
specified a file that is read-only.
- ou --or-
path
especificou um arquivo que está oculto.path
specified a file that is hidden.
path
é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos, conforme definido por InvalidPathChars.path
is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path
é null
.path
is null
.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).
Ocorreu um erro de E/S ao criar o arquivo.An I/O error occurred while creating the file.
path
está em um formato inválido.path
is in an invalid format.
Comentários
O parâmetro path
é permitido para especificar informações de caminho relativo ou absoluto.The path
parameter is permitted to specify relative or absolute path information. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.To obtain the current working directory, see GetCurrentDirectory.
Esse método é equivalente à sobrecarga do construtor de FileStream(String, FileMode, FileAccess, FileShare, Int32).This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare, Int32) constructor overload. Se o arquivo especificado não existir, ele será criado; Se ele existir e não for somente leitura, o conteúdo será substituído.If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.
Por padrão, o acesso completo de leitura/gravação para novos arquivos é concedido a todos os usuários.By default, full read/write access to new files is granted to all users. O arquivo é aberto com acesso de leitura/gravação e deve ser fechado para que possa ser aberto por outro aplicativo.The file is opened with read/write access and must be closed before it can be opened by another application.
Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.
Segurança
FileIOPermission
para obter permissão para ler e gravar no arquivo descrito pelo parâmetro path
.for permission to read and write to the file described by the path
parameter. Ação de segurança: Solicitar.Security action: Demand. Enumerações associadas: Read, WriteAssociated enumerations: Read, Write