当前位置: 移动技术网 > IT编程>开发语言>c# > C# 下载文件 删除文件 写入文本的实例

C# 下载文件 删除文件 写入文本的实例

2019年07月18日  | 移动技术网IT编程  | 我要评论

由于经常用到文件处理,便自己封装了下 分享给大家。 包含写入文本 批量删除文件 下载文件 。--可直接使用

/// <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# 下载文件 删除文件 写入文本的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网