C# 文件操做(上傳,下載,讀取,寫入)

1. 經過byte[]數據下載文件(這種方法可用於以開放Api的形式傳遞文件內容)html

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. 根據路勁,從服務器下載文件web

跨域

/// <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, 0, 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下載服務器

參考另外一篇博文app

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

 


5. 若是是用的.NET MVC3(及以上) 一切變得更加簡單函數

例如post

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 = 2;

        /// <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 * 1024 * 1024)
            {
                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[100];

//讀取文件
FileStream fs = new FileStream(FILE_PATH,FileMode.Open);
byte[] tmpData = new byte[fs.Length];
char[] charData = new char[fs.Length];
fs.Read(tmpData, 0, 100); 
//解碼
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(tmpData, 0, tmpData.Length, charData, 0);

Console.WriteLine(charData);

 

 


 接下來還有經過BufferedStream 讀寫文件的方式,未完待續

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

相關文章
相關標籤/搜索