次の方法で共有


File.Open メソッド (String, FileMode, FileAccess, FileShare)

読み取り、書き込み、または読み取り/書き込みアクセスを持つ指定モードと指定した共有オプションで、指定したパスの FileStream を開きます。

Overloads Public Shared Function Open( _
   ByVal path As String, _   ByVal mode As FileMode, _   ByVal access As FileAccess, _   ByVal share As FileShare _) As FileStream
[C#]
public static FileStream Open(stringpath,FileModemode,FileAccessaccess,FileShareshare);
[C++]
public: static FileStream* Open(String* path,FileModemode,FileAccessaccess,FileShareshare);
[JScript]
public static function Open(
   path : String,mode : FileMode,access : FileAccess,share : FileShare) : FileStream;

パラメータ

  • path
    開くファイル。
  • mode
    ファイルが存在しない場合にファイルを作成するかどうかを指定し、既存のファイルの内容を保持するか上書きするかを決定する FileMode 値。
  • access
    ファイルで実行できる操作を指定する FileAccess 値。
  • share
    他のレッドがファイルに対して持つアクセス タイプを指定する FileShare 値。

戻り値

読み取り、書き込み、または読み取り/書き込みアクセスを持つ指定モードと指定した共有オプションを持つ、指定したパスの FileStream

例外

例外の種類 条件
ArgumentException path が、長さが 0 の文字列であるか、空白しか含んでいないか、または InvalidPathChars で定義されている無効な文字を 1 つ以上含んでいます。

または

accessRead を指定し、 modeCreateCreateNewTruncate 、または Append を指定しました。

ArgumentNullException path が null 参照 (Visual Basic では Nothing) です。
PathTooLongException 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。
DirectoryNotFoundException 割り当てられていないドライブであるなど、指定されたパスが無効です。
IOException ファイルを開くときに、I/O エラーが発生しました。
UnauthorizedAccessException path によって、読み取り専用のファイルが指定され、 accessRead ではありません。

または

path によってディレクトリが指定されました。

または

呼び出し元に、必要なアクセス許可がありません。

ArgumentOutOfRangeException modeaccess 、または share によって無効な値が指定されました。
FileNotFoundException path で指定されたファイルが見つかりませんでした。
NotSupportedException path の形式が無効です。

解説

path パラメータは、相対パス情報または絶対パス情報を指定することを許可されています。相対パス情報は、現在の作業ディレクトリに対して相対的に解釈されます。現在の作業ディレクトリを取得するには、 GetCurrentDirectory のトピックを参照してください。

このメソッドの使用例については、以下の「使用例」を参照してください。その他の一般的な I/O タスクまたは関連する I/O タスクの例を次の表に示します。

実行するタスク 参考例があるトピック
テキスト ファイルを作成する。 ファイルへのテキストの書き込み
テキスト ファイルに書き込む。 ファイルへのテキストの書き込み
テキスト ファイルから読み取る。 ファイルからのテキストの読み取り
テキストをファイルに追加する。 ログ ファイルのオープンと追加

File.AppendText

FileInfo.AppendText

ファイルの名前を変更、またはファイルを移動する。 File.Move

FileInfo.MoveTo

ファイルをコピーする。 File.Copy

FileInfo.CopyTo

ファイルのサイズを取得する。 FileInfo.Length
ファイルの属性を取得する。 File.GetAttributes
ファイルの属性を設定する。 File.SetAttributes
ファイルが存在するかどうかを判別する。 File.Exists
バイナリ ファイルから読み取る。 新しく作成したデータ ファイルの読み取りと書き込み
バイナリ ファイルに書き込む。 新しく作成したデータ ファイルの読み取りと書き込み
ディレクトリを作成する。 CreateDirectory

Directory

使用例

[Visual Basic, C#, C++] ファイル共有を禁止して、ファイルを読み取り専用アクセスで開く例を次に示します。

 
Imports System
Imports System.IO
Imports System.Text

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

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

        ' Open the stream and read it back.
        fs = File.Open(path, FileMode.Open, FileAccess.Read)
        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.
            Dim fs2 As FileStream = File.Open(path, FileMode.Open)
            ' Do some task here.
            fs2.Close()
        Catch e As Exception
            Console.Write("Opening the file twice is disallowed.")
            Console.WriteLine(", as expected: {0}", e.ToString())
        End Try

        fs.Close()
    End Sub
End Class

[C#] 
using System;
using System.IO;
using System.Text;

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

        // Delete the file if it exists.
        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());
            }
        }
    }
}

[C++] 
#using <mscorlib.dll>

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

int main() {
    String* path = S"c:\\temp\\MyTest.txt";

    // Delete the file if it exists.
    if (!File::Exists(path)) {
        // Create the file.
        FileStream* fs = File::Create(path);
        try {
            Byte info[] = (new UTF8Encoding(true))->GetBytes(S"This is some text in the file.");

            // Add some information to the file.
            fs->Write(info, 0, info->Length);
        } __finally {
            if (fs) __try_cast<IDisposable*>(fs)->Dispose();
        }
    }

    // Open the stream and read it back.
    FileStream* fs = File::Open(path, FileMode::Open, FileAccess::Read, FileShare::None);
    try {
        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.
            FileStream* fs2 = File::Open(path, FileMode::Open);
            try {
                // Do some task here.
            } __finally {
                if (fs2) __try_cast<IDisposable*>(fs2)->Dispose();
            }
        } catch (Exception* e) {
            Console::Write(S"Opening the file twice is disallowed.");
            Console::WriteLine(S", as expected: {0}", e);
        }
    } __finally {
        if (fs) __try_cast<IDisposable*>(fs)->Dispose();
    }
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET, Common Language Infrastructure (CLI) Standard

.NET Framework セキュリティ:

参照

File クラス | File メンバ | System.IO 名前空間 | File.Open オーバーロードの一覧 | 入出力操作 | ファイルからのテキストの読み取り | ファイルへのテキストの書き込み