.NET中的文件IO操作实例

1.写入文件代码:

 //1.1 生成文件名和设置文件物理路径
Random random = new Random(DateTime.Now.Millisecond);
string fileName = System.DateTime.Now.ToString("yyMMddHHmmss")+random.Next();
string PhysicalPath = Server.MapPath("../File/Template/productDetails/" + fileName + ".txt"); //1.2 判断文件是否存在
if (!File.Exists(PhysicalPath))
{
FileStream fs = new FileStream(PhysicalPath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.Write(proDetails);
sw.Close();
fs.Close();
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "addAtt", "<script>alert('添加失败,请重试!');location.href='#'</script>");
}

2.读取文件代码:

 //将商品详情写入文件中
string detailsPath=CreateFile(proDetails);
string filePath = Server.MapPath("../File/Template/productDetails/" + detailsPath+".txt");
if (File.Exists(url))
{
// Create the file.
using (FileStream fs=new FileStream(url,FileMode.Open))
{
StreamReader sr=new StreamReader(fs,Encoding.Default);
this.aaa.InnerHtml = sr.ReadToEnd();
sr.Close();
}
}

3. 删除文件:

 //1.1 生成文件名和设置文件物理路径
string phpPath=Server.MapPath(path);
if (File.Exists(phpPath))
{
File.Delete(phpPath);
}
上一篇:[Vijos 1143]三取方格数


下一篇:selenium 爬虫