C# 文件操作(上传,下载,读取,写入)

1. 通过byte[]数据下载文件(这种方法可用于以开放Api的形式传递文件内容)

public void FileDownLoadByByte(byte[] fileData, string fileName)
{
  //添加这个编码可以防止在IE下文件名乱码的问题
  fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); Response.Clear();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AppendHeader("Content-Length", fileData.Length.ToString());
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
}

  


2. 根据路劲,从服务器下载文件

/// <summary>
/// 从服务器下载文件
/// </summary>
/// <param name="fileName">客户端保存的文件名</param>
/// <param name="serverFilePath">服务器端要下载的文件路径</param>
protected void LoadFileFromServer(string fileName, string serverFilePath)
{
FileInfo fileInfo = new FileInfo(serverFilePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}

/// <summary>
/// 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite
/// 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。
/// 将后台文件写入 HTTP 响应输出流(不在内存中进行缓冲)
/// </summary>
public void TransmitFile()
{
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("Content-Disposition", "attachment;filename=download.zip");
string filename = Server.MapPath("~/Download/xx.zip");
Response.TransmitFile(filename);
}

3. 通过流的形式下载文件

public void LoadFileByStream()
{
string fileName = "aaa.txt";//客户端保存的文件名
string filePath = Server.MapPath("~/Download/xx.txt"); //以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, , bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}

4. Excel下载

参考另一篇博文

http://www.cnblogs.com/TiestoRay/archive/2013/02/02/2576134.html


5. 如果是用的.NET MVC3(及以上) 一切变得更加简单

例如

public ActionResult LoadFile2()
{
string filePath = Server.MapPath("~/Download/xx.jpg");
return File(filePath, "application/x-jpg", "demo.jpg");
}

它共有六种可用形式

FileContentResult File(byte[] fileContents, string contentType);
FileStreamResult File(Stream fileStream, string contentType);
FilePathResult File(string fileName, string contentType);
virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);
virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);

6. Ftp文件处理

参考 C#Ftp文件处理


7. 文件上传

将这种稍作修改即可解决跨域文件上传的问题,具体内容参考  跨域文件上传解决方案

后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace SmsWebSystem.Upload
{
/// <summary>
/// FileHandler 的摘要说明
/// </summary>
public class FileHandler : IHttpHandler
{
private const int MAX_UPLOAD_SIZE = ; /// <summary>
/// fileSelector是前台代码中文件控件的name
/// </summary>
/// <param name="req"></param>
/// <param name="res"></param>
/// <returns></returns>
public string UploadFile(HttpRequest req ,HttpResponse res)
{
if (req.Files["fileSelector"].ContentLength > MAX_UPLOAD_SIZE * * )
{
return String.Format("请上传{0}M以内的文件。", MAX_UPLOAD_SIZE);
} string uploadFileName = req.Files["fileSelector"].FileName;
string path = HttpContext.Current.Server.MapPath(uploadFileName);
req.Files["fileSelector"].SaveAs(path);
return "";
} /// <summary>
/// 需要指定上传结束后的回调函数 这里是uploadCallBack
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
string result = UploadFile(context.Request, context.Response);
if (String.IsNullOrEmpty(result))
{
result = "上传成功";
}
context.Response.Write(String.Format("<script>top.uploadCallBack('{0}');</script>", result));
} public bool IsReusable
{
get
{
return false;
}
}
}
}

前台代码

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="fileform" name = "fileform" enctype="multipart/form-data"
action="FileHandler.ashx" target="hideFrame" method="post">
<input type="file" id="fileSelector" name="fileSelector" />
</form>
<iframe id="hideFrame" name="hideFrame" style="display:none;"></iframe>
<input type="button" id="btnUpload" value="上传" />
</body>
<script>
document.querySelector("#btnUpload").onclick = function () {
this.style.backgroundColor = "blue";
document.querySelector("#fileform").submit();
} function uploadCallBack(rst) {
document.querySelector("#btnUpload").style.backgroundColor = "white";
alert(rst);
}
</script>
</html>

8. 使用文件流写入文件数据

FileStream fs = new FileStream(FILE_PATH,FileMode.OpenOrCreate);

string content = "";//要写入的内容
//获得字节数组
byte [] data =new UTF8Encoding().GetBytes(content); //开始写入,第二个参数用文件流的长度 表示向文件末尾追加内容
fs.Write(data,fs,data.Length); //清空缓冲区
fs.Flush(); //关闭流
fs.Close();

要注意的一点是,如果上传的文件过大,可能会报异常

【HTTP错误404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求,原因是Web服务器上的请求筛选被配置为拒绝该请求,因为内容长度超过配置的值】

需要配置IIS配置文件(%windir%/system32/inetsrv/config/applicationhost.config)及项目配置文件 web.config

具体内容参考 《IIS请求筛选模块被配置为拒绝超过请求内容长度的请


9.使用文件流读取文件数据

byte[] byData = new byte[];

//读取文件
FileStream fs = new FileStream(FILE_PATH,FileMode.Open);
byte[] tmpData = new byte[fs.Length];
char[] charData = new char[fs.Length];
fs.Read(tmpData, , );
//解码
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(tmpData, , tmpData.Length, charData, ); Console.WriteLine(charData);

接下来还有通过BufferedStream 读写文件的方式,未完待续

参考 https://msdn.microsoft.com/zh-cn/library/3dsccbf4(VS.80).aspx

上一篇:Java 异步处理简单实践


下一篇:git clean -fd 命令删除文件之后 项目工程文件恢复