File.Open 方法

定义

打开指定路径上的 FileStreamOpens a FileStream on the specified path.

重载

Open(String, FileMode)

通过不共享的读/写访问权限打开指定路径上的 FileStreamOpens a FileStream on the specified path with read/write access with no sharing.

Open(String, FileMode, FileAccess)

通过指定的模式和不共享的访问权限打开指定路径上的 FileStreamOpens a FileStream on the specified path, with the specified mode and access with no sharing.

Open(String, FileMode, FileAccess, FileShare)

打开指定路径上的 FileStream,具有带读、写或读/写访问的指定模式和指定的共享选项。Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

Open(String, FileMode)

通过不共享的读/写访问权限打开指定路径上的 FileStreamOpens a FileStream on the specified path with read/write access with no sharing.

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileMode mode);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode);
static member Open : string * System.IO.FileMode -> System.IO.FileStream
Public Shared Function Open (path As String, mode As FileMode) As FileStream

参数

path
String

要打开的文件。The file to open.

mode
FileMode

FileMode 值,用于指定在文件不存在时是否创建该文件,并确定是保留还是覆盖现有文件的内容。A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.

返回

以读/写访问与不共享权限打开的指定模式和路径上的 FileStreamA FileStream opened in the specified mode and path, with read/write access and not shared.

异常

path 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

pathnullpath 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).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 指定了一个只读文件。path specified a file that is read-only.

-or- 当前平台不支持此操作。This operation is not supported on the current platform.

-or- path 指定了一个目录。path specified a directory.

-or- 调用方没有所要求的权限。The caller does not have the required permission.

-or- modeCreate ,且指定的文件是一个隐藏文件。mode is Create and the specified file is a hidden file.

mode 指定了一个无效值。mode specified an invalid value.

未找到 path 中指定的文件。The file specified in path was not found.

path 的格式无效。path is in an invalid format.

示例

下面的代码示例创建一个临时文件并向其中写入一些文本。The following code example creates a temporary file and writes some text to it. 然后,该示例使用 T:System.IO.FileMode.Open 打开该文件;也就是说,如果该文件不存在,则不会创建它。The example then opens the file, using T:System.IO.FileMode.Open; that is, if the file did not already exist, it would not be created.

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

int main()
{
   // Create a temporary file, and put some data into it.
   String^ path = Path::GetTempFileName();
   FileStream^ fs = File::Open( path, FileMode::Open, FileAccess::Write, FileShare::None );
   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.
   fs = File::Open( path, FileMode::Open );
   try
   {
      array<Byte>^b = gcnew array<Byte>(1024);
      UTF8Encoding^ temp = gcnew UTF8Encoding( true );
      while ( fs->Read( b, 0, b->Length ) > 0 )
      {
         Console::WriteLine( temp->GetString( b ) );
      }
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }
}
using System;
using System.IO;
using System.Text;

class Test 
{
    public static void Main() 
    {
        // Create a temporary file, and put some data into it.
        string path = Path.GetTempFileName();
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None)) 
        {
            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 (FileStream fs = File.Open(path, FileMode.Open)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
  
    ' Create a temporary file, and put some data into it. 
    Dim path1 As String = Path.GetTempFileName()
    Using fs As FileStream = File.Open(path1, FileMode.Open, FileAccess.Write, FileShare.None)
      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 fs As FileStream = File.Open(path1, FileMode.Open)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)
      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop
    End Using

  End Sub
End Class

注解

允许 path 参数指定相对或绝对路径信息。The path parameter is permitted to specify relative or absolute path information. 相对路径信息被解释为相对于当前工作目录。Relative path information is interpreted as relative to the current working directory. 若要获取当前工作目录,请参阅 GetCurrentDirectoryTo obtain the current working directory, see GetCurrentDirectory.

有关常见 i/o 任务的列表,请参阅常见 I/o 任务For a list of common I/O tasks, see Common I/O Tasks.

安全性

FileIOPermission
用于读取和写入指定的文件。for reading from and writing to the specified file. 关联的枚举: ReadWriteAssociated enumerations: Read, Write

另请参阅

Open(String, FileMode, FileAccess)

通过指定的模式和不共享的访问权限打开指定路径上的 FileStreamOpens a FileStream on the specified path, with the specified mode and access with no sharing.

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access);
static member Open : string * System.IO.FileMode * System.IO.FileAccess -> System.IO.FileStream
Public Shared Function Open (path As String, mode As FileMode, access As FileAccess) As FileStream

参数

path
String

要打开的文件。The file to open.

mode
FileMode

FileMode 值,用于指定在文件不存在时是否创建该文件,并确定是保留还是覆盖现有文件的内容。A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.

access
FileAccess

一个 FileAccess 值,它指定可以对文件执行的操作。A FileAccess value that specifies the operations that can be performed on the file.

返回

一个非共享的 FileStream,它提供对指定文件的访问,并且具有指定的模式和访问权限。An unshared FileStream that provides access to the specified file, with the specified mode and access.

异常

path 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

-or- access 指定了 Read ,并且 mode 指定了 CreateCreateNewTruncateAppendaccess specified Read and mode specified Create, CreateNew, Truncate, or Append.

pathnullpath 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).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 指定了一个只读文件,并且 access 不是 Readpath specified a file that is read-only and access is not Read.

-or- path 指定了一个目录。path specified a directory.

-or- 调用方没有所要求的权限。The caller does not have the required permission.

-or- modeCreate,指定文件为隐藏文件。mode is Create and the specified file is a hidden file.

modeaccess 指定了一个无效值。mode or access specified an invalid value.

未找到 path 中指定的文件。The file specified in path was not found.

path 的格式无效。path is in an invalid format.

示例

下面的示例打开一个具有只读访问权限的文件。The following example opens a file with read-only access.


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

int main()
{
    // This sample assumes that you have a folder named "c:\temp" on your computer.
    String^ filePath = "c:\\temp\\MyTest.txt";
    // Delete the file if it exists.
    if (File::Exists( filePath ))
    {
        File::Delete( filePath );
    }
    // Create the file.
    FileStream^ fs = File::Create( filePath );
    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.
    fs = File::Open( filePath, FileMode::Open, FileAccess::Read );
    try
    {
        array<Byte>^ b = gcnew array<Byte>(1024);
        UTF8Encoding^ temp = gcnew UTF8Encoding( true );
        while ( fs->Read( b, 0, b->Length ) > 0 )
        {
            Console::WriteLine( temp->GetString( b ) );
        }
        try
        {
            // Try to write to the file.
            fs->Write( b, 0, b->Length );
        }
        catch ( Exception^ e ) 
        {
            Console::WriteLine( "Writing was disallowed, as expected: {0}", e->ToString() );
        }
    }
    finally
    {
        if ( fs )
            delete (IDisposable^)fs;
    }
}
using System;
using System.IO;
using System.Text;

class Test 
{
    public static void Main() 
    {
        // This sample assumes that you have a folder named "c:\temp" on your computer.
        string filePath = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(filePath)) 
        {
            File.Delete(filePath);
        }
        
        // Create the file.
        using (FileStream fs = File.Create(filePath)) 
        {
            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 (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }

            try 
            {
                // Try to write to the file.
                fs.Write(b,0,b.Length);
            } 
            catch (Exception e) 
            {
                Console.WriteLine("Writing was disallowed, as expected: {0}", e.ToString());
            }
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    ' This sample assumes that you have a folder named "c:\temp" on your computer. 
    Dim filePath As String = "c:\temp\MyTest.txt"

    ' Delete the file if it exists. 
    If File.Exists(filePath) Then
      File.Delete(filePath)
    End If

    ' Create the file.
    Using fs As FileStream = File.Create(filePath)
      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 fs As FileStream = File.Open(filePath, FileMode.Open, FileAccess.Read)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)

      ' Display the information on the console. 
      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop

      Try
        ' Try to write to the file
        fs.Write(b, 0, b.Length)
      Catch e As Exception
        Console.WriteLine("Writing was disallowed, as expected: " & e.ToString())
      End Try

    End Using

  End Sub
End Class

注解

允许 path 参数指定相对或绝对路径信息。The path parameter is permitted to specify relative or absolute path information. 相对路径信息被解释为相对于当前工作目录。Relative path information is interpreted as relative to the current working directory. 若要获取当前工作目录,请参阅 GetCurrentDirectoryTo obtain the current working directory, see GetCurrentDirectory.

安全性

FileIOPermission
用于读取和写入指定的文件。for reading from and writing to the specified file. 关联的枚举: ReadWriteAssociated enumerations: Read, Write

另请参阅

Open(String, FileMode, FileAccess, FileShare)

打开指定路径上的 FileStream,具有带读、写或读/写访问的指定模式和指定的共享选项。Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);
static member Open : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare -> System.IO.FileStream
Public Shared Function Open (path As String, mode As FileMode, access As FileAccess, share As FileShare) As FileStream

参数

path
String

要打开的文件。The file to open.

mode
FileMode

FileMode 值,用于指定在文件不存在时是否创建该文件,并确定是保留还是覆盖现有文件的内容。A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.

access
FileAccess

一个 FileAccess 值,它指定可以对文件执行的操作。A FileAccess value that specifies the operations that can be performed on the file.

share
FileShare

一个 FileShare 值,它指定其他线程所具有的对该文件的访问类型。A FileShare value specifying the type of access other threads have to the file.

返回

指定路径上的 FileStream,具有带读、写或读/写访问的指定模式以及指定的共享选项。A FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

异常

path 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

-or- access 指定了 Read ,并且 mode 指定了 CreateCreateNewTruncateAppendaccess specified Read and mode specified Create, CreateNew, Truncate, or Append.

pathnullpath 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).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 指定了一个只读文件,并且 access 不是 Readpath specified a file that is read-only and access is not Read.

-or- path 指定了一个目录。path specified a directory.

-or- 调用方没有所要求的权限。The caller does not have the required permission.

-or- modeCreate,指定文件为隐藏文件。mode is Create and the specified file is a hidden file.

modeaccessshare 指定了一个无效值。mode, access, or share specified an invalid value.

未找到 path 中指定的文件。The file specified in path was not found.

path 的格式无效。path is in an invalid format.

示例

下面的示例打开一个具有只读访问权限且不允许文件共享的文件。The following example opens a file with read-only access and with file sharing disallowed.

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

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Create the file if it does not exist.
   if (  !File::Exists( path ) )
   {
      // Create the file.
      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.
   FileStream^ fs = File::Open( path, FileMode::Open, FileAccess::Read, FileShare::None );
   try
   {
      array<Byte>^b = gcnew array<Byte>(1024);
      UTF8Encoding^ temp = gcnew UTF8Encoding( true );
      while ( fs->Read( b, 0, b->Length ) > 0 )
      {
         Console::WriteLine( temp->GetString( b ) );
      }
      try
      {
         // Try to get another handle to the same file.
         FileStream^ fs2 = File::Open( path, FileMode::Open );
         try
         {
            // Do some task here.
         }
         finally
         {
            if ( fs2 )
                        delete (IDisposable^)fs2;
         }
      }
      catch ( Exception^ e ) 
      {
         Console::Write( "Opening the file twice is disallowed." );
         Console::WriteLine( ", as expected: {0}", e );
      }
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }
}
using System;
using System.IO;
using System.Text;

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

        // Create the file if it does not exist.
        if (!File.Exists(path)) 
        {
            // Create the file.
            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 (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }

            try 
            {
                // Try to get another handle to the same file.
                using (FileStream fs2 = File.Open(path, FileMode.Open)) 
                {
                    // Do some task here.
                }
            } 
            catch (Exception e) 
            {
                Console.Write("Opening the file twice is disallowed.");
                Console.WriteLine(", as expected: {0}", e.ToString());
            }
        }
    }
}
Imports System.IO
Imports System.Text

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

    ' Create the file if it does not exist. 
    If Not File.Exists(path) Then
      ' Create the file.
      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
    End If

    ' Open the stream and read it back.
    Using fs As FileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)

      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop

      Try
        ' Try to get another handle to the same file. 
        Using fs2 As FileStream = File.Open(path, FileMode.Open)
          ' Do some task here.
        End Using
      Catch e As Exception
        Console.Write("Opening the file twice is disallowed.")
        Console.WriteLine(", as expected: {0}", e.ToString())
      End Try

    End Using

  End Sub
End Class

注解

允许 path 参数指定相对或绝对路径信息。The path parameter is permitted to specify relative or absolute path information. 相对路径信息被解释为相对于当前工作目录。Relative path information is interpreted as relative to the current working directory. 若要获取当前工作目录,请参阅 GetCurrentDirectoryTo obtain the current working directory, see GetCurrentDirectory.

有关常见 i/o 任务的列表,请参阅常见 I/o 任务For a list of common I/O tasks, see Common I/O Tasks.

安全性

FileIOPermission
用于读取和写入指定的文件。for reading from and writing to the specified file. 关联的枚举: ReadWriteAssociated enumerations: Read, Write

另请参阅

适用于