File.WriteAllLines(String,IEnumerable
句法:
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable
参数:该函数接受两个参数,如下所示:
- path: This is the specified file where collection of strings are going to be written.
- contents: This is the specified lines to write to the file.
例外情况:
- ArgumentException:路径是长度为零的字符串,仅包含空格,或由GetInvalidPathChars()方法定义的一个或多个无效字符。
- ArgumentNullException:路径或内容为null。
- DirectoryNotFoundException:路径无效。
- IOException:打开文件时发生I / O错误。
- PathTooLongException:路径超出了系统定义的最大长度。
- NotSupportedException:路径格式无效。
- SecurityException:调用者没有所需的权限。
- UnauthorizedAccessException:该路径指定了一个只读文件。或路径指定了隐藏的文件。或当前平台不支持此操作。或路径是目录。或呼叫者没有所需的权限。
下面是说明File.WriteAllLines(String,IEnumerable)方法的程序。
程序1:在运行以下代码之前,将创建一个文件file.txt ,其内容将被过滤,如下所示-
在代码下方,其自身创建了一个新文件gfg.txt ,其中包含过滤后的字符串。
// C# program to illustrate the usage
// of File.WriteAllLines(String,
// IEnumerable) method
// Using System, System.IO
// and System.Linq namespaces
using System;
using System.IO;
using System.Linq;
class GFG {
// Specifying a file from where
// some contents are going to be filtered
static string Path = @"file.txt";
static void Main(string[] args)
{
// Reading content of file.txt
var da = from line in File.ReadLines(Path)
// Selecting lines started with "G"
where(line.StartsWith("G"))
select line;
// Creating a new file gfg.txt with the
// filtered contents
File.WriteAllLines(@"gfg.txt", da);
Console.WriteLine("Writing the filtered collection "+
"of strings to the file has been done.");
}
}
输出:
Writing the filtered collection of strings to the file has been done.
运行上面的代码后,将显示上面的输出,并创建一个新文件gfg.txt,如下所示-
程序2:在运行以下代码之前,创建了两个文件file.txt和gfg.txt ,其中一些内容如下所示-
下面的代码用文件file.txt的选定内容覆盖文件gfg.txt 。
// C# program to illustrate the usage
// of File.WriteAllLines(String,
// IEnumerable) method
// Using System, System.IO
// and System.Linq namespaces
using System;
using System.IO;
using System.Linq;
class GFG {
// Specifying a file from where
// some contents are going to be filtered
static string Path = @"file.txt";
static void Main(string[] args)
{
// Reading the contents of file.txt
var da = from line in File.ReadLines(Path)
// Selecting lines started with "g"
where(line.StartsWith("g"))
select line;
// Overwriting the file gfg.txt with the
// selected string of the file file.txt
File.WriteAllLines(@"gfg.txt", da);
Console.WriteLine("Overwriting the selected collection"+
" of strings to the file has been done.");
}
}
输出:
Overwriting the selected collection of strings to the file has been done.
运行上述代码后,将显示以上输出,文件gfg.txt的内容如下所示: