Asp.Net常用文件操作方法

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Web;

using System.Net;

using System.Threading;

using EcmaScript.NET;

using Yahoo.Yui.Compressor;

using System.Xml;

using System.Data.OleDb;

using System.Data;

using System.Collections;

using System.Web.UI.HtmlControls;

using System.Drawing.Imaging;

namespace Common

{

public class fileHelper

{

#region 下载文件

/// <summary>

///功能说明:文件下载类--不管是什么格式的文件,都能够弹出打开/保存窗口,

///包括使用下载工具下载

///继承于IHttpHandler接口,可以用来自定义HTTP 处理程序同步处理HTTP的请求

/// </summary>

/// <param name="context"></param>

public static void ProcessRequest(HttpContext context)

{

HttpResponse Response = context.Response;

HttpRequest Request = context.Request;

System.IO.Stream iStream = null;

byte[] buffer = new Byte[10240];

int length;

long dataToRead;

try

{

string filename = Request["fn"];

string filepath = HttpContext.Current.Server.MapPath("~/") + filename; //待下载的文件路径

iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,

System.IO.FileAccess.Read, System.IO.FileShare.Read);

Response.Clear();

dataToRead = iStream.Length;

long p = 0;

if (Request.Headers["Range"] != null)

{

Response.StatusCode = 206;

p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));

}

if (p != 0)

{

Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());

}

Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());

Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename))));

iStream.Position = p;

dataToRead = dataToRead - p;

while (dataToRead > 0)

{

if (Response.IsClientConnected)

{

length = iStream.Read(buffer, 0, 10240);

Response.OutputStream.Write(buffer, 0, length);

Response.Flush();

buffer = new Byte[10240];

dataToRead = dataToRead - length;

}

else

{

dataToRead = -1;

}

}

}

catch (Exception ex)

{

Response.Write("Error : " + ex.Message);

}

finally

{

if (iStream != null)

{

iStream.Close();

}

Response.End();

}

}

/// <summary>

/// 下载方法二

/// </summary>

/// <param name="_Request"></param>

/// <param name="_Response"></param>

/// <param name="_fileName"></param>

/// <param name="_fullPath"></param>

/// <param name="_speed"></param>

/// <returns></returns>

public static bool ResponseFile(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);

try

{

_Response.AddHeader("Accept-Ranges", "bytes");

_Response.Buffer = false;

long fileLength = myFile.Length;

long startBytes = 0;

double pack = 10240; //10K bytes

//int sleep = 200;   //每秒5次   即5*10K bytes每秒

int sleep = (int)Math.Floor(1000 * pack / _speed) + 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);

int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

for (int i = 0; i < maxCount; i++)

{

if (_Response.IsClientConnected)

{

_Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));

Thread.Sleep(sleep);

}

else

{

i = maxCount;

}

}

}

catch

{

return false;

}

finally

{

br.Close();

myFile.Close();

}

}

catch

{

return false;

}

return true;

}

/// <summary>

/// 从图片地址下载图片到本地磁盘

/// </summary>

/// <param name="ToLocalPath">图片本地磁盘地址</param>

/// <param name="Url">图片网址</param>

/// <returns></returns>

public static bool SavePhotoFromUrl(string FileName, string Url)

{

bool Value = false;

WebResponse response = null;

Stream stream = null;

try

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

response = request.GetResponse();

stream = response.GetResponseStream();

if (!response.ContentType.ToLower().StartsWith("text/"))

{

Value = SaveBinaryFile(response, FileName);

}

}

catch (Exception err)

{

//Common.PageValidate.WriteFile("下载错误:" + err.Message.ToString());

}

return Value;

}

/// <summary>

/// Save a binary file to disk.

/// </summary>

/// <param name="response">The response used to save the file</param>

// 将二进制文件保存到磁盘

private static bool SaveBinaryFile(WebResponse response, string FileName)

{

bool Value = true;

byte[] buffer = new byte[1024];

try

{

if (File.Exists(FileName))

{

File.Delete(FileName);

}

Stream outStream = System.IO.File.Create(FileName);

Stream inStream = response.GetResponseStream();

int l;

do

{

l = inStream.Read(buffer, 0, buffer.Length);

if (l > 0)

outStream.Write(buffer, 0, l);

}

while (l > 0);

outStream.Close();

inStream.Close();

}

catch (Exception ex)

{

Value = false;

}

return Value;

}

#endregion

#region 抓取网页数据

/// <summary>

/// 获取网页数据

/// </summary>

/// <param name="PageURL"></param>

/// <returns></returns>

public static string GetPageCode(string PageURL)

{

string Charset = "gb2312";

try

{

//存放目标网页的html

String strHtml = "";

//连接到目标网页

HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(PageURL);

wreq.Headers.Add("X_FORWARDED_FOR", "101.0.0.11"); //发送X_FORWARDED_FOR头(若是用取源IP的方式,可以用这个来造假IP,对日志的记录无效)

wreq.Method = "Get";

wreq.KeepAlive = true;

wreq.ContentType = "application/x-www-form-urlencoded";

wreq.AllowAutoRedirect = true;

wreq.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";

wreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";

CookieContainer cookieCon = new CookieContainer();

wreq.CookieContainer = cookieCon;

HttpWebResponse wresp = null;

try

{

wresp = (HttpWebResponse)wreq.GetResponse();

}

catch (WebException ex)

{

wresp = (HttpWebResponse)ex.Response;

}

//采用流读取,并确定编码方式

Stream s = wresp.GetResponseStream();

StreamReader objReader = new StreamReader(s, System.Text.Encoding.GetEncoding(Charset));

string strLine = "";

//读取

while (strLine != null)

{

strLine = objReader.ReadLine();

if (strLine != null)

{

strHtml += strLine + "\r\n";

}

}

return strHtml;

}

catch (Exception n) //遇到错误,打印错误

{

return n.Message;

}

}

#endregion

#region 压缩合并cssjs文件

/// <summary>

/// 压缩合并css文件

/// </summary>

/// <param name="filePath"></param>

/// <param name="cssContent"></param>

/// <returns></returns>

public static bool CompressCssFile(string filePath, ref string cssContent)

{

bool ret = true;

try

{

//目录不存在

string[] pathList = filePath.Split(‘,‘);

//获取该文件夹下所有js或者css文件

HttpContext ctx = HttpContext.Current;

string newDir = ctx.Server.MapPath("../style/");

string filetype = ".min.css";

string newFileName = GetNewFileName(filePath);

string newFilePath = newDir + newFileName + filetype;

if (File.Exists(newFilePath))

{

FileInfo Nowinfo = new FileInfo(newFilePath);

cssContent = File.ReadAllText(Nowinfo.FullName, Encoding.UTF8);

return true;

}

foreach (string path in pathList)

{

if (ctx.Server.MapPath(path) != "")

{

FileInfo info = new FileInfo(ctx.Server.MapPath(path));

string strContent = File.ReadAllText(info.FullName, Encoding.UTF8);

if (info.Extension.ToLower() == ".css")

{

if (!info.FullName.ToLower().EndsWith(".no.css"))

{

if (!info.FullName.ToLower().EndsWith(".min.css"))

{

strContent = CssCompressor.Compress(strContent);

}

cssContent += strContent;

}

}

}

}

var newFile = new FileInfo(newFilePath);

File.WriteAllText(newFile.FullName, cssContent, Encoding.UTF8);

}

catch (Exception ex)

{ ret = false; }

return ret;

}

/// <summary>

/// 压缩合并js文件

/// </summary>

/// <param name="filePath"></param>

/// <param name="jsContent"></param>

/// <returns></returns>

public static bool CompressJsFile(string filePath, ref string jsContent)

{

bool ret = true;

try

{

//目录不存在

string[] pathList = filePath.Split(‘,‘);

//获取该文件夹下所有js或者css文件

HttpContext ctx = HttpContext.Current;

string newDir = ctx.Server.MapPath("../scripts/");

string filetype = ".min.js";

string newFileName = GetNewFileName(filePath);

string newFilePath = newDir + newFileName + filetype;

if (File.Exists(newFilePath))

{

FileInfo Nowinfo = new FileInfo(newFilePath);

jsContent = File.ReadAllText(Nowinfo.FullName, Encoding.UTF8);

return true;

}

foreach (string path in pathList)

{

if (ctx.Server.MapPath(path) != "")

{

FileInfo info = new FileInfo(ctx.Server.MapPath(path));

string strContent = File.ReadAllText(info.FullName, Encoding.UTF8);

if (info.Extension.ToLower() == ".js")

{

if (!info.FullName.ToLower().EndsWith(".no.js"))

{

if (!info.FullName.ToLower().EndsWith(".min.js"))

{

var js = new JavaScriptCompressor(strContent, false, Encoding.UTF8, System.Globalization.CultureInfo.CurrentCulture);

strContent = js.Compress();

}

jsContent += "\n" + strContent;

}

}

}

}

var newFile = new FileInfo(newFilePath);

File.WriteAllText(newFile.FullName, jsContent, Encoding.UTF8);

}

catch (Exception ex)

{ ret = false; }

return ret;

}

/// <summary>

/// 获取压缩后新文件的名称

/// </summary>

/// <param name="filePath"></param>

/// <returns></returns>

public static string GetNewFileName(string filePath)

{

string[] pathList = filePath.Split(‘,‘);

//获取该文件夹下所有js或者css文件

HttpContext ctx = HttpContext.Current;

string newFileName = "";

foreach (string path in pathList)

{

if (ctx.Server.MapPath(path) != "")

{

FileInfo info = new FileInfo(ctx.Server.MapPath(path));

newFileName += info.Name.Replace(info.Extension, "") + "_";

}

}

newFileName = newFileName.Remove(newFileName.Length - 1, 1);

return newFileName;

}

#endregion

#region 导入导出Excel

/// <summary>

/// 获取Excel文件数据表列表

/// </summary>

public static ArrayList GetExcelTables(string ExcelFileName)

{

DataTable dt = new DataTable();

ArrayList TablesList = new ArrayList();

if (File.Exists(ExcelFileName))

{

using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))

{

try

{

conn.Open();

dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

}

catch (Exception exp)

{

throw exp;

}

//获取数据表个数

int tablecount = dt.Rows.Count;

for (int i = 0; i < tablecount; i++)

{

string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd(‘$‘);

if (TablesList.IndexOf(tablename) < 0)

{

TablesList.Add(tablename);

}

}

}

}

return TablesList;

}

#endregion

#region 普通文件操作

/// <summary>

/// 备份文件

/// </summary>

/// <param name="sourceFileName">源文件名</param>

/// <param name="destFileName">目标文件名</param>

/// <param name="overwrite">当目标文件存在时是否覆盖</param>

/// <returns>操作是否成功</returns>

public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)

{

if (!System.IO.File.Exists(sourceFileName))

{

throw new FileNotFoundException(sourceFileName + "文件不存在!");

}

if (!overwrite && System.IO.File.Exists(destFileName))

{

return false;

}

try

{

System.IO.File.Copy(sourceFileName, destFileName, true);

return true;

}

catch (Exception e)

{

throw e;

}

}

#endregion

#region 文件上传

/// <summary>

/// 是否允许该扩展名上传

/// </summary>

/// <param name="hifile"></param>

/// <returns></returns>

public static bool IsAllowedExtension(HtmlInputFile hifile)

{

string strOldFilePath = "", strExtension = "";

//允许上传的扩展名,可以改成从配置文件中读出

string[] arrExtension = { ".gif", ".GIF", ".JPG", ".jpg", ".JPEG", ".BMP", ".PNG", ".jpeg", ".bmp", ".png" };

if (hifile.PostedFile.FileName != string.Empty)

{

strOldFilePath = hifile.PostedFile.FileName;

//取得上传文件的扩展名

strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));

//判断该扩展名是否合法

for (int i = 0; i < arrExtension.Length; i++)

{

if (strExtension.Equals(arrExtension[i]))

{

return true;

}

}

}

return false;

}

/// <summary>

/// 判断上传文件大小是否超过最大值

/// </summary>

/// <param name="hifile"></param>

/// <returns></returns>

public static bool IsAllowedLength(HtmlInputFile hifile)

{

//允许上传文件大小的最大值,可以保存在xml文件中,单位为KB

int i = 512;

//如果上传文件的大小超过最大值,返回flase,否则返回true.

if (hifile.PostedFile.ContentLength > i * 512)

{

return false;

}

return true;

}

/// <summary>

/// 上传文件返回新文件名

/// </summary>

/// <param name="hifile"></param>

/// <param name="strAbsolutePath"></param>

/// <returns></returns>

public static string SaveFile(HtmlInputFile hifile, string strAbsolutePath)

{

string strOldFilePath = "", strExtension = "", strNewFileName = "";

if (hifile.PostedFile.FileName != string.Empty)

{

strOldFilePath = hifile.PostedFile.FileName;

//取得上传文件的扩展名

strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));

//文件上传后的命名

strNewFileName = GetUniqueString() + strExtension;

if (strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)

{

hifile.PostedFile.SaveAs(strAbsolutePath + strNewFileName);

}

else

{

hifile.PostedFile.SaveAs(strAbsolutePath + "\\" + strNewFileName);

}

}

return strNewFileName;

}

/// <summary>

/// 删除指定文件

/// </summary>

/// <param name="strAbsolutePath"></param>

/// <param name="strFileName"></param>

public static void DeleteFile(string strAbsolutePath, string strFileName)

{

if (strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)

{

if (File.Exists(strAbsolutePath + strFileName))

{

File.Delete(strAbsolutePath + strFileName);

}

}

else

{

if (File.Exists(strAbsolutePath + "\\" + strFileName))

{

File.Delete(strAbsolutePath + "\\" + strFileName);

}

}

}

/// <summary>

/// 删除文件夹下面的文件

/// </summary>

/// <param name="path"></param>

public static void DeleteFilePath(string path)

{

string[] fileList = Directory.GetFiles(path);

foreach (string str in fileList)

{

File.Delete(str);

}

}

/// <summary>

/// 获取不重复文件名

/// </summary>

/// <returns></returns>

public static string GetUniqueString()

{

return DateTime.Now.ToString("yyyyMMddhhmmssff");

}

#endregion

/// <summary>

/// 将 Stream 转成 byte[]

/// </summary>

public static byte[] StreamToBytes(Stream stream)

{

byte[] bytes = new byte[stream.Length];

stream.Read(bytes, 0, bytes.Length);

// 设置当前流的位置为流的开始

stream.Seek(0, SeekOrigin.Begin);

return bytes;

}

/// <summary>

/// 将 byte[] 转成 Stream

/// </summary>

public static Stream BytesToStream(byte[] bytes)

{

Stream stream = new MemoryStream(bytes);

return stream;

}

}

}

				
时间: 2024-11-03 03:42:38

Asp.Net常用文件操作方法的相关文章

php 常用文件操作方法

<?php header("Content-type: text/html; charset=utf-8"); ###########init################ $file='/Users/M/Sites/demo/test.php'; $dir ='/Users/M/Sites/demo'; $deldir ='/Users/M/Sites/demo/js'; ###########文件属性操作################ /*文件属性获取*/ //getFi

C#File类常用的文件操作方法(创建、移动、删除、复制等)

File类,是一个静态类,主要是来提供一些函数库用的.静态实用类,提供了很多静态的方法,支持对文件的基本操作,包括创建,拷贝,移动,删除和 打开一个文件. File类方法的参量很多时候都是路径path.File的一些方法可以返回FileStream和StreamWriter的对象.可以 和他们配套使用.System.IO.File类和System.IO.FileInfo类 主要提供有关文件的各种操作,在使用时需要引用System.IO命名空间. 一.File类常用的操作方法 1.创建文件方法 /

如何学习ASP Global.asa 文件?

ASP Global.asa 文件 Previous Page Next Page Global.asa 文件是一个可选的文件,它可包含可被 ASP 应用 程序中每个页面访问的对象.变量以及方法的声明. Global.asa 文件 Global.asa 文件是一个可选的文件,它可包含可被 ASP 应用程序中每个页面访问的对象. 变量以及方法的声明.所有合法的浏览器脚本都能在 Global.asa 中使用. Global.asa 文件可包含下列内容: Application 事件 Session

ASP.NET常用内置对象

ASP.NET 常用内置对象:Response对象.Request对象.Session对象.Server对象.Application对象 1.Response对象: (1) 用于向浏览器输出信息 常用的方法是:Response.Write()方法,例如:Response.Write("Hello"); Response.Write(“<b>当前时间是:</b>"+DateTime.Now); (2)利用Response.Redirect()方法进行页面

ASP.NET常用数据绑定控件优劣总结

本文的初衷在于对Asp.net常用数据绑定控件进行一个概览性的总结,主要分析各种数据绑定控件各自的优缺点,以便在实际的开发中选用合适的控件进行数据绑定,以提高开发效率. 因为这些数据绑定控件大部分都已经封装的很好了,稍微有一些基础的朋友都可以很容易的上手使用,所以本文不涉及具体控件的使用,只在于分析各自的优劣点,但是在下一篇文章里,我会主要讲一下ListBox.GridView.Repeater这三个数据绑定控件的“高效分页”,ListBox和GridView内置的有分页,但是其效率太低了,少量

ASP.NET常用数据绑定控件优缺点分析总结

ASP.NET常用数据绑定控件优缺点分析总结 本文的初衷在于对Asp.net常用数据绑定控件进行一个概览性的总结,主要分析各种数据绑定控件各自的优缺点,以便在实际的开发中选用合适的控件进行数据绑定,以提高开发效率. 因为这些数据绑定控件大部分都已经封装的很好了,稍微有一些基础的朋友都可以很容易的上手使用,所以本文不涉及具体控件的使用,只在于分析各自的优劣点,但是在下一篇文章里,我会主要讲一下ListBox.GridView.Repeater这三个数据绑定控件的“高效分页”,ListBox和Gri

基于asp.net 的文件上传和下载~~~转

基于asp.net 的文件上传和下载 摘要: 文件的上传和下载是网络中非常重要的两种应用, 本文介绍了使用asp.net 控件实现文件上传的基本方法.解决了当上传大文件时出现各种问题, 并给出了几种解决方案和技巧.另外, 下载文件用二进制读写的方式实现. 1 引言          文件的上传和下载是网络中非常重要的两种应用.其实现方法主要有FTP 方式和HTTP 方式两种, FTP( File Transfer Protocol)是指文件传输协议, 主要用来在网络上传输文件.这种方式虽说文件传

asp.net webconfig文件详解

asp.net webconfig文件详解 一.认识Web.config文件 Web.config 文件是一个xml文本文件,它用来储存 asp.NET Web 应用程序的配置信息(如最常用的设置asp.NET Web 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中.当你通过.NET新建一个Web应用程序后,默认情况下会在根目录自动创建一个默认的Web.config文件,包括默认的配置设置,所有的子目录都继承它的配置设置.如果你想修改子目录的配置设置,你可以在该子目录下新建一个We

ASP.NET常用标准配置web.config

在我们的项目开发过程中,我们经常要配置wei.config文件,而大多数的时候配置差不多,下面的是一个简单的配置,其他的配置可以在这个基础上在添加 <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <!-- 动态调试编译 设置 compilation debug="true" 以启用 ASPX 调试.否则,将此值设置为