C#ファイル処理関連整理(アップロード、ダウンロード、読み取り)

20278 ワード

1.byte[]データからファイルをダウンロードする
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, 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のダウンロード
http://www.cnblogs.com/TiestoRay/archive/2013/02/02/2576134.html
 
5.もし使うなら.NET MVC 3(以上)すべてが簡単になります
たとえば
public ActionResult LoadFile2()

{

    string filePath = Server.MapPath("~/Download/xx.jpg");

    return File(filePath, "application/x-jpg", "demo.jpg");

}
6つの使用可能な形式があります
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>