namespace Filenew
{
class Program
{
static void Main(string[] args)
{
string path = @"c:/users/shenbao/others/shen.txt";
try
{
File.Delete(path);
}
catch (Exception ex)
{
Console.WriteLine("没有找到指定的文件", ex.ToString());
}
//第一种方法
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("shenbaoaizhengqiaoling");
}
}
try
{
File.Delete(path);
}
catch (Exception ex)
{
Console.WriteLine("没有找到指定的文件", ex.ToString());
}
//第二种方法
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
byte[] mybyte = Encoding.GetEncoding("gb2312").GetBytes("shenbaoaizhengqiaoling");
fs.Write(mybyte,0,mybyte.Length);
fs.Flush();
fs.Close();
}
//追加新的内容
StreamReader sr = File.OpenText(path);
string old = sr.ReadToEnd();
Console.WriteLine(old);
string news ="zhidaoyongyuan";
old += news;
Console.WriteLine(old);
sr.Close();
StreamWriter sWriter = File.CreateText(path);
sWriter.WriteLine(old);
sWriter.Flush();
//关闭之前打开的文件资源(写入命令)
sWriter.Close();
sr = File.OpenText(path);
old = sr.ReadToEnd();
Console.WriteLine(old);
Console.ReadLine();
}
}
}