您的位置:首页 > 其它

.NET中的文件IO操作实例

2014-09-18 09:47 387 查看
1.写入文件代码:

//1.1 生成文件名和设置文件物理路径
Random random = new Random(DateTime.Now.Millisecond);
string fileName = System.DateTime.Now.ToString("yyMMddHHmmss")+random.Next(10000);
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: