FileSystem.FileOpen 方法

定義

開啟一個輸入或輸出檔案。 這個 My 功能能讓你在檔案 I/O 操作 FileOpen中提升生產力和效能。 如需詳細資訊,請參閱FileSystem

public static void FileOpen(int FileNumber, string FileName, Microsoft.VisualBasic.OpenMode Mode, Microsoft.VisualBasic.OpenAccess Access = Microsoft.VisualBasic.OpenAccess.Default, Microsoft.VisualBasic.OpenShare Share = Microsoft.VisualBasic.OpenShare.Default, int RecordLength = -1);
static member FileOpen : int * string * Microsoft.VisualBasic.OpenMode * Microsoft.VisualBasic.OpenAccess * Microsoft.VisualBasic.OpenShare * int -> unit
Public Sub FileOpen (FileNumber As Integer, FileName As String, Mode As OpenMode, Optional Access As OpenAccess = Microsoft.VisualBasic.OpenAccess.Default, Optional Share As OpenShare = Microsoft.VisualBasic.OpenShare.Default, Optional RecordLength As Integer = -1)

參數

FileNumber
Int32

必須的。 任何有效的檔案號碼。 使用該 FreeFile 函數取得下一個可用的檔案號。

FileName
String

必須的。 指定檔名的字串表達式——可能包含目錄或資料夾,以及磁碟機。

Mode
OpenMode

必須的。 列舉指定檔案模式:Append、、BinaryInputOutput、或Random。 如需詳細資訊,請參閱OpenMode

Access
OpenAccess

Optional. 列舉指定對開啟檔案允許的操作: Read、、 WriteReadWrite。 預設為 ReadWrite。 如需詳細資訊,請參閱OpenAccess

Share
OpenShare

Optional. 列舉指定其他程序不允許對開啟檔案進行的操作:SharedLock ReadLock WriteLock Read Write和 。 預設為 Lock Read Write。 如需詳細資訊,請參閱OpenShare

RecordLength
Int32

Optional. ) 小於或等於32,767個 (位元組的數字。 對於隨機開啟的檔案,這個值就是記錄長度。 對於連續檔案,這個值是緩衝的字元數。

例外狀況

記錄長度為負值(且不等於 -1)。

FileName 已經開啟,或 FileName 是無效。

範例

此範例說明了該 FileOpen 函式在啟用檔案輸入與輸出時的各種用途。

以下程式碼會以模式開啟檔案TestFileInput

FileOpen(1, "TESTFILE", OpenMode.Input)
' Close before reopening in another mode.
FileClose(1)

此範例以僅用於寫入操作的模式開啟檔案 Binary

FileOpen(1, "TESTFILE", OpenMode.Binary, OpenAccess.Write)
' Close before reopening in another mode.
FileClose(1)

以下範例以模式開啟檔案 Random 。 該檔案包含結構 Person的紀錄。

Structure Person
    <VBFixedString(30)> Dim Name As String
    Dim ID As Integer
End Structure
Public Sub ExampleMethod()
    ' Count 30 for the string, plus 4 for the integer.
    FileOpen(1, "TESTFILE", OpenMode.Random, , , 34)
    ' Close before reopening in another mode.
    FileClose(1)
End Sub

此程式碼範例以模式開啟檔案 Output ;任何程序都能讀寫檔案。

FileOpen(1, "TESTFILE", OpenMode.Output, OpenAccess.Default, OpenShare.Shared)
' Close before reopening in another mode.
FileClose(1)

此程式碼範例以讀取模式開啟檔案 Binary ;其他程序無法讀取檔案。

FileOpen(1, "TESTFILE", OpenMode.Binary, OpenAccess.Read,
   OpenShare.LockRead)

備註

此功能 FileOpen 是為了向下相容而設計,可能會影響效能。 對於非傳統應用程式,物件 My.Computer.FileSystem 提供更好的效能。 欲了解更多資訊,請參閱檔案存取Visual Basic

您必須先開啟檔案,才能對其執行任何 I/O 操作。 FileOpen 為檔案分配一個 I/O 緩衝區,並決定與緩衝區共用的存取模式。

Important

在寫入檔案時,如果應用程式嘗試寫入的檔案不存在,則可能需要建立檔案。 為此,需要取得該檔案所建立目錄的權限。 然而,如果指定的檔案 FileName 確實存在,應用程式只需 Write 對該檔案本身的權限。 為了提升安全性,盡可能在部署時建立檔案,並只授予 Write 該檔案權限,而非整個目錄。 為了提升安全性,建議將資料寫入使用者目錄,而非根目錄或程式檔案目錄。

開啟通道可透過使用該 FreeFile() 函數找到。

Important

FileOpen 函式需要 ReadFileIOPermissionAccess 列舉中取得存取,這可能會影響部分信任情況下的執行。 更多資訊請參見 FileIOPermissionAccess 列舉。

適用於

另請參閱