C# 下载文件 删除文件 写入文本
由于经常用到文件处理,便自己封装了下 分享给大家。 包含写入文本 批量删除文件 下载文件 。--可直接使用
/// <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;
}
}