FileInfo.Open 方法

定義

使用各種讀取/寫入和共用權限來開啟檔案。

多載

Open(FileMode)

使用指定模式來開啟檔案。

Open(FileStreamOptions)

使用指定的建立模式、讀取/寫入和共用許可權,初始化 類別的新實例 FileStream ,其他 FileStreams 的存取權可以相同檔案、緩衝區大小、其他檔案選項和配置大小。

Open(FileMode, FileAccess)

使用讀取、寫入或讀取/寫入存取,並以指定模式來開啟檔案。

Open(FileMode, FileAccess, FileShare)

使用讀取、寫入或讀取/寫入存取和指定的共用選項,將檔案開啟於指定模式中。

Open(FileMode)

來源:
FileInfo.cs
來源:
FileInfo.cs
來源:
FileInfo.cs

使用指定模式來開啟檔案。

public:
 System::IO::FileStream ^ Open(System::IO::FileMode mode);
public System.IO.FileStream Open (System.IO.FileMode mode);
member this.Open : System.IO.FileMode -> System.IO.FileStream
Public Function Open (mode As FileMode) As FileStream

參數

mode
FileMode

FileMode 常數,指定用於開啟檔案的模式 (例如,OpenAppend)。

傳回

以指定模式開啟的檔案,其使用讀取/寫入存取且為不共用。

例外狀況

找不到檔案。

檔案是唯讀的或為目錄。

指定的路徑無效,例如位於未對應的磁碟機上。

檔案已經開啟。

範例

下列範例會開啟檔案、將一些資訊新增至檔案,並讀取檔案。

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

int main()
{
   String^ path = "c:\\MyTest.txt";
   FileInfo^ fi = gcnew FileInfo( path );
   
   // Delete the file if it exists.
   if (  !fi->Exists )
   {
      //Create the file.
      FileStream^ fs = fi->Create();
      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 = fi->Open( 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;
   }
}

//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
//
using System;
using System.IO;
using System.Text;

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

        // Delete the file if it exists.
        if (!fi.Exists)
        {
            //Create the file.
            using (FileStream fs = fi.Create())
            {
                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 = fi.Open(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));
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim fi As FileInfo = New FileInfo(path)
        Dim fs As FileStream

        ' Delete the file if it exists.
        If fi.Exists = False Then
            'Create the file.
            fs = fi.Create()
            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)
            fs.Close()
        End If

        'Open the stream and read it back.
        fs = fi.Open(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
        fs.Close()
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is some text in the file.
'
'
'
'
'
'
'
'
'
'
'
'

另請參閱

適用於

Open(FileStreamOptions)

來源:
FileInfo.cs
來源:
FileInfo.cs
來源:
FileInfo.cs

使用指定的建立模式、讀取/寫入和共用許可權,初始化 類別的新實例 FileStream ,其他 FileStreams 的存取權可以相同檔案、緩衝區大小、其他檔案選項和配置大小。

public:
 System::IO::FileStream ^ Open(System::IO::FileStreamOptions ^ options);
public System.IO.FileStream Open (System.IO.FileStreamOptions options);
member this.Open : System.IO.FileStreamOptions -> System.IO.FileStream
Public Function Open (options As FileStreamOptions) As FileStream

參數

options
FileStreamOptions

物件,描述要使用的選擇性 FileStream 參數。

傳回

FileStream 會包裝開啟的檔案。

備註

FileStream(String, FileStreamOptions) 如需例外狀況的相關資訊。

適用於

Open(FileMode, FileAccess)

來源:
FileInfo.cs
來源:
FileInfo.cs
來源:
FileInfo.cs

使用讀取、寫入或讀取/寫入存取,並以指定模式來開啟檔案。

public:
 System::IO::FileStream ^ Open(System::IO::FileMode mode, System::IO::FileAccess access);
public System.IO.FileStream Open (System.IO.FileMode mode, System.IO.FileAccess access);
member this.Open : System.IO.FileMode * System.IO.FileAccess -> System.IO.FileStream
Public Function Open (mode As FileMode, access As FileAccess) As FileStream

參數

mode
FileMode

FileMode 常數,指定用於開啟檔案的模式 (例如,OpenAppend)。

access
FileAccess

FileAccess 常數,指定是否以 ReadWriteReadWrite 檔案存取來開啟檔案。

傳回

FileStream 物件,開啟於指定模式和存取中,且為不共用。

例外狀況

呼叫端沒有必要的權限。

找不到檔案。

Name 是唯讀或為目錄。

指定的路徑無效,例如位於未對應的磁碟機上。

檔案已經開啟。

Name 是空的,或者只含有泛空白字元。

一或多個引數是 Null。

範例

下列範例會以唯讀方式開啟檔案,並從檔案讀取。

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

int main()
{
   String^ path = "c:\\MyTest.txt";
   FileInfo^ fi = gcnew FileInfo( path );
   
   // Delete the file if it exists.
   if (  !fi->Exists )
   {
      
      //Create the file.
      FileStream^ fs = fi->Create();
      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 = fi->Open( 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 );
      }
   }
   finally
   {
      if ( fs )
         delete (IDisposable^)fs;
   }
}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
//Writing was disallowed, as expected: System.NotSupportedException: Stream does 
//not support writing.
//   at System.IO.__Error.WriteNotSupported()
//   at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
//   at main() in c:\documents and settings\MyComputer\my documents\
//visual studio 2005\projects\finfo open2\finfo open2\
//cpp_console_application.cpp:line 46
using System;
using System.IO;
using System.Text;

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

        // Delete the file if it exists.
        if (!fi.Exists)
        {
            //Create the file.
            using (FileStream fs = fi.Create())
            {
                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 = fi.Open(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());
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
//Writing was disallowed, as expected: System.NotSupportedException: Stream does
//not support writing.
//   at System.IO.__Error.WriteNotSupported()
//   at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
//   at Test.Main() in C:\Documents and Settings\My Computer\My Documents\
//Visual Studio 2005\Projects\finfo open2\finfo open2\Program.cs:line 39
imports System.IO
imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\MyTest.txt"
        Dim fi As FileInfo = new FileInfo(path)
        Dim fs As FileStream

        ' Delete the file if it exists.
        If fi.Exists = False
            'Create the file.
            fs = fi.Create()
            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)
            fs.Close()
        End If

        'Open the stream and read it back.
        fs = fi.Open(FileMode.Open, FileAccess.Read)
        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
                fs.Write(b,0,b.Length)
                Catch e As Exception
                Console.WriteLine("Writing was disallowed, as expected: {0}", e.ToString())
            End Try
        fs.Close()
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is some text in the file.
'
'
'
'
'
'
'
'
'
'
'
'
'Writing was disallowed, as expected: System.NotSupportedException: Stream does 
'not support writing.
'   at System.IO.__Error.WriteNotSupported()
'   at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
'   at VB_Console_Application.Test.Main() in C:\Documents and Settings\MyComputer
'\My Documents\Visual Studio 2005\Projects\finfo open2\finfo open2\Module1.vb:line 34
'

另請參閱

適用於

Open(FileMode, FileAccess, FileShare)

來源:
FileInfo.cs
來源:
FileInfo.cs
來源:
FileInfo.cs

使用讀取、寫入或讀取/寫入存取和指定的共用選項,將檔案開啟於指定模式中。

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

參數

mode
FileMode

FileMode 常數,指定用於開啟檔案的模式 (例如,OpenAppend)。

access
FileAccess

FileAccess 常數,指定是否以 ReadWriteReadWrite 檔案存取來開啟檔案。

share
FileShare

FileShare 常數,指定其他 FileStream 物件對這個檔案的存取類型。

傳回

FileStream 物件,以指定的模式、存取和共用選項開啟。

例外狀況

呼叫端沒有必要的權限。

找不到檔案。

Name 是唯讀或為目錄。

指定的路徑無效,例如位於未對應的磁碟機上。

檔案已經開啟。

Name 是空的,或者只含有泛空白字元。

一或多個引數是 Null。

範例

下列範例示範開啟檔案以供讀取和寫入,但不允許存取其他使用者或進程。

using namespace System;
using namespace System::IO;
int main()
{
   
   // Open an existing file, or create a new one.
   FileInfo^ fi = gcnew FileInfo( "temp.txt" );
   
   // Open the file just specified such that no one else can use it.
   FileStream^ fs = fi->Open( FileMode::OpenOrCreate, FileAccess::ReadWrite, FileShare::None );
   
   // Create another reference to the same file.
   FileInfo^ nextfi = gcnew FileInfo( "temp.txt" );
   try
   {
      
      // Try opening the same file, which was locked by the previous process.
      nextfi->Open( FileMode::OpenOrCreate, FileAccess::Read );
      Console::WriteLine( "The file was not locked, and was opened by a second process." );
   }
   catch ( IOException^ ) 
   {
      Console::WriteLine( "The file could not be opened because it was locked by another process." );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e );
   }

   
   // Close the file so it can be deleted.
   fs->Close();
}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//The file could not be opened because it was locked by another process.
using System;
using System.IO;

public class OpenTest
{
    public static void Main()
    {
        // Open an existing file, or create a new one.
        FileInfo fi = new FileInfo("temp.txt");

        // Open the file just specified such that no one else can use it.
        FileStream fs = fi.Open( FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None );

        // Create another reference to the same file.
        FileInfo nextfi = new FileInfo("temp.txt");

        try
        {
            // Try opening the same file, which was locked by the previous process.
            nextfi.Open( FileMode.OpenOrCreate, FileAccess.Read );

            Console.WriteLine("The file was not locked, and was opened by a second process.");
        }
        catch (IOException)
        {
            Console.WriteLine("The file could not be opened because it was locked by another process.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        // Close the file so it can be deleted.
        fs.Close();
    }
}

//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The file could not be opened because it was locked by another process.
Imports System.IO

Public Class OpenTest

    Public Shared Sub Main()
        ' Open an existing file, or create a new one.
        Dim fi As New FileInfo("temp.txt")

        ' Open the file just specified such that no one else can use it.
        Dim fs As FileStream = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)

        ' Create another reference to the same file.
        Dim nextfi As New FileInfo("temp.txt")

        Try
            ' Try opening the same file, which was locked by the previous process.
            nextfi.Open(FileMode.OpenOrCreate, FileAccess.Read)
            Console.WriteLine("The file was not locked, and was opened by a second process.")
        Catch i as IOException
            Console.WriteLine(i.ToString())
        Catch e As Exception
            Console.WriteLine(e.ToString())
        End Try

        ' Close the file so it can be deleted.
        fs.Close()
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'System.IO.IOException: The process cannot access the file 
''C:\Documents and Settings\mydirectory\My Documents\Visual Studio 2005
'\Projects\fileinfoopen\fileinfoopen\obj\Release\temp.txt' 
'because it is being used by another process.
'at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
'at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, 
'Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
'options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
'at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,
'FileShare share) at System.IO.FileInfo.Open(FileMode mode, FileAccess access)
'at VB_Console_Application.OpenTest.Main() in C:\Documents and Settings
'\mydirectory\My Documents\Visual Studio 2005\Projects\VB_Console_Application
'\VB_Console_Application\Module1.vb:line 19

另請參閱

適用於