FileInfo.Open メソッド

定義

さまざまな読み取り/書き込みおよび共有権限を持つファイルを開きます。

オーバーロード

名前 説明
Open(FileMode)

指定したモードでファイルを開きます。

Open(FileMode, FileAccess)

読み取り、書き込み、または読み取り/書き込みアクセスを使用して、指定したモードでファイルを開きます。

Open(FileMode, FileAccess, FileShare)

読み取り、書き込み、または読み取り/書き込みアクセスと、指定した共有オプションを使用して、指定したモードでファイルを開きます。

Open(FileMode)

指定したモードでファイルを開きます。

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

ファイルを開くモード (OpenAppendなど) を指定するFileMode定数。

返品

指定したモードで開かれたファイル。読み取り/書き込みアクセスと共有解除が行われます。

例外

ファイルが見つかりません。

ファイルが読み取り専用であるか、ディレクトリです。

マップされていないドライブ上など、指定されたパスが無効です。

ファイルは既に開いています。

次の例では、ファイルを開き、ファイルに情報を追加して、ファイルを読み取ります。

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

読み取り、書き込み、または読み取り/書き込みアクセスを使用して、指定したモードでファイルを開きます。

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

ファイルを開くモード (OpenAppendなど) を指定するFileMode定数。

access
FileAccess

ReadWrite、またはファイル アクセスを使用してファイルを開くか、ReadWriteするかを指定するFileAccess定数。

返品

指定したモードとアクセスで開かれた FileStream オブジェクト。共有解除されます。

例外

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

ファイルが見つかりません。

Name が読み取り専用であるか、ディレクトリです。

マップされていないドライブ上など、指定されたパスが無効です。

ファイルは既に開いています。

Name が空であるか、空白のみが含まれています。

1 つ以上の引数が null です。

次の例では、ファイルを読み取り専用として開き、ファイルから読み取ります。

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)

読み取り、書き込み、または読み取り/書き込みアクセスと、指定した共有オプションを使用して、指定したモードでファイルを開きます。

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

ファイルを開くモード (OpenAppendなど) を指定するFileMode定数。

access
FileAccess

ReadWrite、またはファイル アクセスを使用してファイルを開くか、ReadWriteするかを指定するFileAccess定数。

share
FileShare

他のFileStream オブジェクトがこのファイルに対して持つアクセスの種類を指定するFileShare定数。

返品

指定したモード、アクセス、および共有オプションで開かれた FileStream オブジェクト。

例外

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

ファイルが見つかりません。

Name が読み取り専用であるか、ディレクトリです。

マップされていないドライブ上など、指定されたパスが無効です。

ファイルは既に開いています。

Name が空であるか、空白のみが含まれています。

1 つ以上の引数が null です。

次の例では、読み取りと書き込みのためにファイルを開きますが、他のユーザーまたはプロセスへのアクセスを禁止します。

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

こちらもご覧ください

適用対象