File.ReadLines(String)是一個內置的File類方法,用於讀取文件的行。
用法:
public static System.Collections.Generic.IEnumerable ReadLines (string path);
參數:此函數接受如下所示的參數:
- path: This is the specified file for reading.
異常:
- ArgumentException:路徑為長度為零的字符串,僅包含空格,或由GetInvalidPathChars()方法定義的一個或多個無效字符。
- ArgumentNullException:路徑為空。
- DirectoryNotFoundException:路徑無效。
- FileNotFoundException:找不到路徑指定的文件。
- IOException:打開文件時發生I /O錯誤。
- PathTooLongException:路徑超過最大長度system-defined。
- SecurityException:調用者沒有所需的權限。
- UnauthorizedAccessException:該路徑指定一個隻讀文件。或者當前平台不支持此操作。或路徑是目錄。或調用者沒有所需的權限。
返回值:返回指定文件的所有行。
下麵是說明File.ReadLines(String)方法的程序。
程序1:最初,將創建一個文件file.txt,其內容如下所示-
// C# program to illustrate the usage
// of File.ReadLines(String) method
// Using System and System.IO namespaces
using System;
using System.IO;
public class GFG {
public static void Main(String[] argv)
{
// Calling the ReadLines(String) function
foreach(string line in File.ReadLines(@"file.txt"))
{
// Printing the file contents
Console.WriteLine(line);
}
}
}
輸出:
GFG gfg Geeks GeeksforGeeks geeksforgeeks
程序2:最初,將創建一個文件file.txt,其內容如下所示-
下麵的代碼從文件中過濾掉一些內容,然後將它們打印回去。
// C# program to illustrate the usage
// of File.ReadLines(String) method
// Using System and System.IO namespaces
using System;
using System.IO;
public class GFG {
public static void Main(String[] argv)
{
// Calling the ReadLines(String) function
foreach(string line in File.ReadLines(@"file.txt"))
{
// Filtering the file contents and printing
if (line.Contains("GFG")) {
Console.WriteLine(line);
}
}
}
}
輸出:
GFG
相關用法
- C# MathF.Exp()用法及代碼示例
- C# MathF.Abs()用法及代碼示例
- C# Uri.GetLeftPart()用法及代碼示例
- C# MathF.Tan()用法及代碼示例
- C# MathF.Cos()用法及代碼示例
- C# MathF.Pow()用法及代碼示例
- C# MathF.Min()用法及代碼示例
- C# Uri.HexUnescape()用法及代碼示例
- C# Uri.ReferenceEquals()用法及代碼示例
- C# MathF.Max()用法及代碼示例
- C# MathF.Log()用法及代碼示例
- C# MathF.Sin()用法及代碼示例
- C# MathF.Acos()用法及代碼示例
- C# Object.GetHashCode()用法及代碼示例
- C# Object.GetTypeCode()用法及代碼示例
- C# MathF.Acosh()用法及代碼示例
- C# File.Exists()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.ReadLines(String) Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。