码迷,mamicode.com
首页 > Windows程序 > 详细

c#文件 IO类基本操作

时间:2020-03-01 17:07:42      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:string   tac   saveas   creat   ali   ISE   mode   txt   context   

using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Threading;

namespace HuoLi.Common
{
    /// <summary>
    /// file 的摘要说明。
    /// </summary>
    public class MyFile
    {
        public MyFile()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        public static string UpExcel(string SaveFolder, System.Web.UI.WebControls.FileUpload upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.PostedFile.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
            if (ext != "xml")
            {
                return string.Empty;
            }
            else
            {
                string ss = System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Year.ToString() + "-" + System.DateTime.Now.Hour.ToString() + "-" + System.DateTime.Now.Minute.ToString() + "-" + System.DateTime.Now.Second.ToString() + "-" + System.DateTime.Now.Millisecond.ToString();
                fileName = ss + "." + ext;
                CreateFolder(SaveFolder);
                string saveP = HttpContext.Current.Request.PhysicalApplicationPath + SaveFolder + fileName;
                DelImgFileByPhy(saveP);
                upControl.PostedFile.SaveAs(saveP);
                return fileName;
            }
            //}
        }
        public static string UpImgFile(string SaveFolder, long MaxSize, System.Web.UI.WebControls.FileUpload upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.PostedFile.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
            if (ext != "jpg" && ext != "jpeg" && ext != "gif" && ext != "png" && ext != "swf")
            {
                return string.Empty;
            }
            else
            {
                if (upControl.FileBytes.Length <= MaxSize)
                {
                    //Guid.NewGuid().ToString("N")
                    fileName = GetDateFileName() + "." + ext;
                    CreateFolder(SaveFolder);
                    string saveP = System.Web.HttpContext.Current.Server.MapPath(SaveFolder) + fileName;
                    DelImgFileByPhy(saveP);
                    upControl.PostedFile.SaveAs(saveP);
                    return fileName;
                }
            }
            return string.Empty;
            //}
        }
        public static string UserUpImgFile(string SaveFolder, long MaxSize, System.Web.UI.WebControls.FileUpload upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.PostedFile.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
            if (ext != "jpg" && ext != "jpeg" && ext != "gif" && ext != "png")
            {
                return string.Empty;
            }
            else
            {
                if (upControl.FileBytes.Length <= MaxSize)
                {
                    //Guid.NewGuid().ToString("N")
                    fileName = GetDateFileName() + "." + ext;
                    CreateFolder(SaveFolder);
                    string saveP = System.Web.HttpContext.Current.Server.MapPath(SaveFolder) + fileName;
                    DelImgFileByPhy(saveP);
                    upControl.PostedFile.SaveAs(saveP);
                    return fileName;
                }
            }
            return string.Empty;
            //}
        }

        public static string UpFile(string SaveFolder, System.Web.UI.HtmlControls.HtmlInputFile upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.PostedFile.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
            if (ext != "jpg" && ext != "jpeg" && ext != "gif")
            {
                return string.Empty;
            }
            else
            {
                fileName = System.Guid.NewGuid().ToString("n") + "." + ext;
                CreateFolder(SaveFolder);
                string saveP = HttpContext.Current.Request.PhysicalApplicationPath + SaveFolder + fileName;
                DelImgFileByPhy(saveP);
                upControl.PostedFile.SaveAs(saveP);
                return fileName;
            }
            //}
        }

        public static string UpFile(string SaveFolder, System.Web.UI.WebControls.FileUpload upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.PostedFile.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
            if (ext != "jpg" && ext != "jpeg" && ext != "gif")
            {
                return string.Empty;
            }
            else
            {
                fileName = System.Guid.NewGuid().ToString("n") + "." + ext;
                CreateFolder(SaveFolder);
                string saveP = HttpContext.Current.Request.PhysicalApplicationPath + SaveFolder + fileName;
                DelImgFileByPhy(saveP);
                upControl.PostedFile.SaveAs(saveP);
                return fileName;
            }
            //}
        }

        public static string UpPdfFile(string SaveFolder, System.Web.UI.WebControls.FileUpload upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.PostedFile.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
            if (ext != "txt" && ext != "pdf" && ext != "zip" && ext != "doc" && ext != "jpg" && ext != "jpeg" && ext != "gif")
            {
                return string.Empty;
            }
            else
            {
                fileName = fileName.Substring(0,fileName.LastIndexOf(.))+GetDateFileName() + "." + ext;
                CreateFolder(SaveFolder);
                string saveP = HttpContext.Current.Request.PhysicalApplicationPath + SaveFolder + fileName;
                DelImgFileByPhy(saveP);
                upControl.PostedFile.SaveAs(saveP);
                return fileName;
            }
            //}
        }

        public static string UpPdfFile(string SaveFolder, HttpPostedFile upControl)
        {
            string fileName = string.Empty;
            //if (!string.IsNullOrEmpty(upControl.PostedFile.FileName))
            //{
            fileName = System.IO.Path.GetFileName(upControl.FileName);
            string ext = fileName.Substring(fileName.LastIndexOf(.) + 1).ToLower();
                fileName = fileName.Substring(0,fileName.LastIndexOf(.))+GetDateFileName() + "." + ext;
                CreateFolder(SaveFolder);
                string saveP = HttpContext.Current.Request.PhysicalApplicationPath + SaveFolder + fileName;
                DelImgFileByPhy(saveP);
                upControl.SaveAs(saveP);
                return fileName;
            //}
        }


        public static string GetDateFileName()
        {
            return DateTime.Now.ToString("yyMMddHHmmssff");
           // return System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Millisecond.ToString();
        }

        //创建文件夹
        public static void CreateFolder(string path)
        {
            string smFolder = System.Web.HttpContext.Current.Server.MapPath(path);
            if (!System.IO.Directory.Exists(smFolder))
            {
                System.IO.Directory.CreateDirectory(smFolder);
            }
        }

 

        //获取物理路径
        public static string GetMapPath(string path)
        {
            return System.Web.HttpContext.Current.Server.MapPath(path);
        }

        //文件存在性
        public static bool ExsitFile(string path)
        {

            return System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(path));
        }

        //删除文件
        public static void DelImgFileByPhy(string PhyFilePath)
        {
            try
            {
                if (System.IO.File.Exists(PhyFilePath))
                {
                    System.IO.File.Delete(PhyFilePath);
                }
            }
            catch
            {
                //    throw ee;
            }
        }

        //删除文件
        public static void DelFile(Object fileSort)
        {
            if (fileSort != null)
            {
                string filepath = fileSort.ToString();
                try
                {
                    if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(filepath)))
                    {
                        System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(filepath));
                    }
                }
                catch
                {
                    //    throw ee;
                }
            }
        }

        /*
           * 输入参数
           * _Request: Page.Request 对象
           * _Response: Page.Response 对象
           * _fileName: 下载文件名
           * _fullPath: 带文件名下载路径
           * _speed 每秒允许下载的字节数
           * 返回是否成功
          * 调用例

          Page.Response.Clear();

          bool success = ResponseFile(Page.Request, Page.Response, "filename", @"C:\download.date", 1024000);

          if(!success) 
              Response.Write("下载文件出错!");

          Page.Response.End();

           */

        public static bool DownFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                #region try2
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    int pack = 10240; //10K bytes 
                    //int sleep = 200; //每秒5次 即5*10K bytes每秒 
                    double v1 = 1000 * pack / _speed;
                    int sleep = (int)Math.Floor(v1) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { =, - });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    double v2 = (fileLength - startBytes) / pack;
                    int maxCount = (int)Math.Floor(v2) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            System.Threading.Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
                #endregion
            }
            catch
            {
                return false;
            }
            return true;
        }


        public static void DownLoadFile(string fileName, HttpResponse Response, HttpServerUtility Server)
        {
            string filePath = Server.MapPath(fileName);
            if (File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码   
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
        }
    }
}

 

c#文件 IO类基本操作

标签:string   tac   saveas   creat   ali   ISE   mode   txt   context   

原文地址:https://www.cnblogs.com/zengxh/p/12390687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!