1.写入文件代码:
1 //1.1 生成文件名和设置文件物理路径 2 Random random = new Random(DateTime.Now.Millisecond); 3 string fileName = System.DateTime.Now.ToString("yyMMddHHmmss")+random.Next(10000); 4 string PhysicalPath = Server.MapPath("../File/Template/productDetails/" + fileName + ".txt"); 5 6 //1.2 判断文件是否存在 7 if (!File.Exists(PhysicalPath)) 8 { 9 FileStream fs = new FileStream(PhysicalPath, FileMode.Create); 10 StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); 11 sw.Write(proDetails); 12 sw.Close(); 13 fs.Close(); 14 } 15 else 16 { 17 Page.ClientScript.RegisterStartupScript(this.GetType(), "addAtt", "<script>alert('添加失败,请重试!');location.href='#'</script>"); 18 }
2.读取文件代码:
1 //将商品详情写入文件中 2 string detailsPath=CreateFile(proDetails); 3 string filePath = Server.MapPath("../File/Template/productDetails/" + detailsPath+".txt"); 4 if (File.Exists(url)) 5 { 6 // Create the file. 7 using (FileStream fs=new FileStream(url,FileMode.Open)) 8 { 9 StreamReader sr=new StreamReader(fs,Encoding.Default); 10 this.aaa.InnerHtml = sr.ReadToEnd(); 11 sr.Close(); 12 } 13 }
3. 删除文件:
1 //1.1 生成文件名和设置文件物理路径 2 string phpPath=Server.MapPath(path); 3 if (File.Exists(phpPath)) 4 { 5 File.Delete(phpPath); 6 }