由于经常用到文件处理,便自己封装了下 分享给大家。 包含写入文本 批量删除文件 下载文件 。--可直接使用
/// <summary>/// 写入到txt/// </summary>/// <param name="savePath"></param>/// <param name="content"></param>public static void WriteInTxt(string savePath, string content){string tempPath = System.IO.Path.GetDirectoryName(savePath);System.IO.Directory.CreateDirectory(tempPath); //创建临时文件目录if (!System.IO.File.Exists(savePath)){FileStream fs1 = new FileStream(savePath, FileMode.Create, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fs1);sw.WriteLine(content);//开始写入值sw.Close();fs1.Close();}else{FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Write);StreamWriter sr = new StreamWriter(fs);sr.WriteLine(content);//开始写入值sr.Close();fs.Close();}}/// <summary>/// 递归删除文件夹下所有文件/// </summary>/// <param name="file"></param>public static void DeleteFile(string dirPath){try{//去除文件夹和子文件的只读属性//去除文件夹的只读属性System.IO.DirectoryInfo fileInfo = new DirectoryInfo(dirPath);fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;//去除文件的只读属性System.IO.File.SetAttributes(dirPath, System.IO.FileAttributes.Normal);//判断文件夹是否还存在if (Directory.Exists(dirPath)){foreach (string f in Directory.GetFileSystemEntries(dirPath)){if (File.Exists(f)){//如果有子文件删除文件File.Delete(f);}else{//循环递归删除子文件夹 DeleteFile(f);}}//删除空文件夹 Directory.Delete(dirPath);}}catch (Exception e){}}/// <summary>/// Http下载文件/// </summary>/// <param name="url">下载文件路径</param>/// <param name="savePath">保存路径</param>/// <returns></returns>public static bool HttpDownloadFile(string url, string savePath){string tempPath = System.IO.Path.GetDirectoryName(savePath);System.IO.Directory.CreateDirectory(tempPath); //创建临时文件目录string tempFile = tempPath + @"/" + System.IO.Path.GetFileName(savePath); //临时文件if (System.IO.File.Exists(tempFile)){//存在则跳出return true;//System.IO.File.Delete(tempFile); }try{FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);// 设置参数HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//发送请求并获取相应回应数据HttpWebResponse response = request.GetResponse() as HttpWebResponse;//直到request.GetResponse()程序才开始向目标网页发送Post请求Stream responseStream = response.GetResponseStream();//创建本地文件写入流//Stream stream = new FileStream(tempFile, FileMode.Create);byte[] bArr = new byte[1024];int size = responseStream.Read(bArr, 0, (int)bArr.Length);while (size > 0){//stream.Write(bArr, 0, size);fs.Write(bArr, 0, size);size = responseStream.Read(bArr, 0, (int)bArr.Length);}//stream.Close();fs.Close();responseStream.Close();System.IO.File.Move(tempFile, savePath);return true;}catch (Exception ex){return false;}}
以上这篇C# 下载文件 删除文件 写入文本的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。
新闻热点
疑难解答