using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string path = @"F:\1.txt"; //指定文件的路径
//----------------------------------------------
//.Exists(path)是判断指定路径下的文件是否存在。
if (System.IO.File.Exists(path))
{
Console.WriteLine("指定路径下的文件存在");
}
else
{
Console.WriteLine("指定路径下的文件不存在");
}
//----------------------------------------------
//将"耐克"这个字符串按照Encoding.Default编码的方式添加到 "path"这个路径对应的文件中去。
//注意:假如F:\1.txt 这个路径不存在1.txt这个文件,它就会给你自动生成一个1.txt文件,然后给“耐克”这个字符串添加进去
System.IO.File.AppendAllText(path, "耐克", Encoding.Default);
//按照Encoding.Default的编码方式读取“path”指定路径下的文件。
string readFile = System.IO.File.ReadAllText(path, Encoding.Default);
Console.WriteLine(readFile);
Console.ReadKey();
}
}
}
WriteAllText与AppendAllText的区别
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//在D盘下创建一个1.txt文件,将"中国"这个字符串写入到文件中,如果D盘下原本就有一个1.txt文件,就将1.txt文件替换掉,然后把"中国"这个字符串写入到文件中。
System.IO.File.WriteAllText(@"d:\1.txt","中国"); //即便程序运行10次,1.txt文件中也只有一个"中国"
//将"中国"这个字符串添加到D盘下的2.txt文件中,如果2.txt不存在,就在D盘下创建2.txt文件,并将"中国"这个字符串追加到2.txt文件中。
System.IO.File.AppendAllText(@"d:\2.txt", "中国");//程序运行10次,2.txt文件中就会有10个"中国",即"中国中国中国中国中国中国中国中国中国中国";
}
}
}