写入操作必须要有该路径的目录,若没有目录将无法进行写入。而对应的文件若没有,会自动的创建。
1、写入读取文本的方法,
// **************** 写入内容 *******************
//向指定路径添加文件,不会覆盖原有内容
AppendAllText(String, String)
//向指定路径添加内容,会覆盖之前的内容。所添加的内容全部在同一行
WriteAllText(String, String)
//向指定路径添加内容,会覆盖之前的内容。字符串数组的每个元素作为一行
WriteAllLines(String, String[])
// ***************** 读取内容 ********************
//读取文件中的所有内容,作为一个字符串
ReadAllText(String)
//读取文件的所有行,返回一个数组,每行内容作为数组的一个元素
ReadAllLines(String)
2、写入实例:
using System;
using System.IO;
namespace WriteFile
{
class Program
{
static void Main(string[] args)
{
string path01 = @"E:\Coding\RecordData\Data01";
string path02 = @"E:\Coding\RecordData\Data02";
string strPath01 = @"E:\Coding\RecordData\Data01\test01.txt";
string strPath02 = @"E:\Coding\RecordData\Data02\test02.txt";
string content01 = "this is test for write files 1 2 3 4 5 6 7 7 8 9";
string[] content02 = { "hello", "this", "just", "a", "test","for it." };
// 判读是否存在该目录
if (!Directory.Exists(path01))
{
Directory.CreateDirectory(path01);
}
if (!Directory.Exists(path02))
{
Directory.CreateDirectory(path02);
}
// 将内容添加到指定的文本中,不会覆盖已有的内容,在文本末尾接着添加
File.AppendAllText(strPath01, content01 + Environment.NewLine);
// 将内容写入到指定的文件中,会覆盖原有的内容
File.WriteAllText(strPath01, content01);
// 将字符串的所有内容都写入指定路径,字符串的每个元素作为一行
File.WriteAllLines(strPath02, content02);
}
}
}