File.Open File.Open File.Open File.Open Method

定義

在指定路徑上開啟 FileStreamOpens a FileStream on the specified path.

多載

Open(String, FileMode) Open(String, FileMode) Open(String, FileMode) Open(String, FileMode)

在指定路徑上開啟具有讀取/寫入權限且不共用的 FileStreamOpens a FileStream on the specified path with read/write access with no sharing.

Open(String, FileMode, FileAccess) Open(String, FileMode, FileAccess) Open(String, FileMode, FileAccess) 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) Open(String, FileMode, FileAccess, FileShare) Open(String, FileMode, FileAccess, FileShare) 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) Open(String, FileMode) Open(String, FileMode) 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 String String String

要開啟的檔案。The file to open.

mode
FileMode FileMode FileMode 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.

傳回

在指定模式和路徑中開啟的 FileStream,具有讀取/寫入存取而且不共用。A 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.

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。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.

找不到 path 指定的檔案。The file specified in path was not found.

範例

下列程式碼範例會建立暫存檔,並寫入一些文字。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
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(1024) 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) Open(String, FileMode, FileAccess) Open(String, FileMode, FileAccess) 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 String String String

要開啟的檔案。The file to open.

mode
FileMode FileMode FileMode 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 FileAccess 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.

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。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.

範例

下列範例會開啟檔案具有唯讀存取權。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
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(1024) 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) Open(String, FileMode, FileAccess, FileShare) Open(String, FileMode, FileAccess, FileShare) 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 String String String

要開啟的檔案。The file to open.

mode
FileMode FileMode FileMode 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 FileAccess FileAccess

FileAccess 值,指定可以在檔案上執行的作業。A FileAccess value that specifies the operations that can be performed on the file.

share
FileShare FileShare FileShare 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.

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。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.

範例

下列範例會開啟檔案具有唯讀存取權,並以檔案共用不允許。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
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(1024) 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

另請參閱

適用於