File.OpenText(String) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
読み取り用の既存の UTF-8 エンコードテキスト ファイルを開きます。
public:
static System::IO::StreamReader ^ OpenText(System::String ^ path);
public static System.IO.StreamReader OpenText(string path);
static member OpenText : string -> System.IO.StreamReader
Public Shared Function OpenText (path As String) As StreamReader
パラメーター
- path
- String
読み取り用に開くファイル。
返品
指定したパス上の StreamReader 。
例外
呼び出し元に必要なアクセス許可がありません。
2.1 より前のバージョンの .NET Framework と .NET Core: path は長さ 0 の文字列で、空白のみを含むか、1 つ以上の無効な文字を含みます。
GetInvalidPathChars() メソッドを使用して、無効な文字のクエリを実行できます。
path は nullです。
指定したパス、ファイル名、またはその両方が、システム定義の最大長を超えています。
指定されたパスが無効です (たとえば、マップされていないドライブ上にあります)。
pathで指定されたファイルが見つかりませんでした。
path が無効な形式です。
例
次の例では、読み取り用のテキスト ファイルを開きます。
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
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 (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
open System.IO
open System.Text
let path = @"c:\temp\MyTest.txt"
if File.Exists path |> not then
// Create the file.
use fs = File.Create path
let info =
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.
do
use sr = File.OpenText path
let mutable s = sr.ReadLine()
while isNull s |> not do
printfn $"{s}"
s <- sr.ReadLine()
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
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 sr As StreamReader = File.OpenText(path)
Do While sr.Peek() >= 0
Console.WriteLine(sr.ReadLine())
Loop
End Using
End Sub
End Class
注釈
このメソッドは、 StreamReader(String) コンストラクターのオーバーロードと同じです。
path パラメーターは、相対パス情報または絶対パス情報を指定できます。 相対パス情報は、現在の作業ディレクトリに対する相対パスとして解釈されます。 現在の作業ディレクトリを取得するには、 GetCurrentDirectoryを参照してください。
一般的な I/O タスクの一覧については、「 一般的な I/O タスク」を参照してください。