【基础巩固】文件流读写、大文件移动 FileStream StreamWriter File Path Directory/ ,m资料管理器(递归)

C#获取文件名 扩展名

string fullPath = @"d:\test\default.avi";

string filename  = Path.GetFileName(fullPath);//返回带扩展名的文件名 "default.avi"
string extension = Path.GetExtension(fullPath);//扩展名 ".aspx"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);// 没有扩展名的文件名 "default" string dirPath = Path.GetDirectoryName(filePath) //返回文件所在目录 "d:\test"
string fullPath1 = Path.Combine(@"d:\test", "default.avi") //返回 "d:\test\default.avi" string fullPath2 = Path.GetFullPath("config.ini");//返回指定路径字符串的绝对路径

测试图片

【基础巩固】文件流读写、大文件移动 FileStream StreamWriter File Path Directory/ ,m资料管理器(递归)

文件流
FileStream 可读可写 大文件 释放
StreamReader 读取 释放
StreamWriter 写入 释放
using 中释放
File 可读可写 小文件

Path类 针对字符串(路径)进行操作

Directory 操作文件夹

文件流读写

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; namespace _09文件流
{
class Program
{
static void Main(string[] args)
{ //string msg = "飞流直下三千尺";
////字符串转字节数组
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg); ////字节数组转字符串 //string str= System.Text.Encoding.UTF8.GetString(buffer); //把字符串写入到文件中,以流的方式写内容 //using ( FileStream fs = new FileStream("1.txt", FileMode.Create, FileAccess.Write))
//{
// string msg = "文能提笔控萝莉";
// byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
// fs.Write(buffer, 0, buffer.Length); //}//Console.ReadKey(); //fs.Close();//关闭流
//fs.Flush();//清除缓冲区
//fs.Dispose();//释放占用的资源 (这三个必须一起写,用using方式就不用这三个释放资源了) //以流的方式读数据 using (FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
string msg = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine(msg);
}
Console.ReadKey(); }
}
}

大文件移动

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _10大文件移动
{
class Program
{
static void Main(string[] args)
{
//读的流
using (FileStream fsRead=new FileStream(@"G:\视频\海盗.mkv",FileMode.Open, FileAccess.Read))
{
//写的流
using (FileStream fsWrite=new FileStream(@"G:\电影\海盗.mkv", FileMode.Create, FileAccess.Write))
{
//每次读取的大小是5M
byte[]buffer=new byte[**];
//实际(真正读取到的大小)
int r= fsRead.Read(buffer, , buffer.Length);
while (r>)
{
//写入
fsWrite.Write(buffer, , r);
Console.WriteLine("**");
//再读取
r = fsRead.Read(buffer, , buffer.Length);
}
}
}
Console.WriteLine("ok了");
Console.ReadKey();
}
}
}

另一种方式的读写

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _11另一种方式的读和写
{
class Program
{
static void Main(string[] args)
{ #region 读取数据
//using (StreamReader reader = new StreamReader("1.txt",Encoding.Default))
//{
//只读取了一行 //string msg= reader.ReadLine();
//string msg;
//要循环读取
//while ((msg=reader.ReadLine())!=null)
//{
// Console.WriteLine(msg);
//}
//一直读取到流的末尾
// string msg= reader.ReadToEnd();
// Console.WriteLine(msg);
//while (!reader.EndOfStream)
//{
// Console.WriteLine(reader.ReadLine());
//} // }
#endregion
#region 写入数据 //using (StreamWriter write=new StreamWriter("one.txt"))
//{
// write.Write("原来这也可以啊");
//} #endregion
// Console.ReadKey(); }
}
}

File(文件) 、Path(路径)类

File:

            //复制
File.Copy(path1, path2); //path1现在有文件路径(带上文件E:\test\test.txt),path2目标文件路径
//创建文件
//File.Create("1.txt");
// File.Delete();//删除
//File.Exists();//判断该路径下的文件是否存在
//File.Move();//移动
//File.WriteAllLines();//
//File.WriteAllText();
// File.ReadAllLines();//
//File.ReadAllText();

Path:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FilePath
{
class Program
{
static void Main(string[] args)
{
string lujing = @"D:\Program Files (x86)\EditPlus 中文版\1.txt";
//主要是更改后缀名
string msg = Path.ChangeExtension(lujing, ".rar");
Console.WriteLine(msg);
string str1 = @"C:\Program Files (x86)\Microsoft\";
string str2 = @"Exchange\Web Services\2.0\GettingStarted.doc";
//合并路径的方法
string msg = Path.Combine(str1, str2);
Console.WriteLine(msg);
string str = @"C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.0\GettingStarted.doc";
//查找某个文件所在的路径.
string msg = Path.GetDirectoryName(str);
Console.WriteLine(msg);
Path.GetExtension();//返回扩展名
//返回的是文件名和扩展名
string msg = Path.GetFileName(str);
Path.GetFileNameWithoutExtension();//只返回文件名
//绝对路径
string msg = Path.GetFullPath("1.txt");
Console.WriteLine(msg); Console.ReadKey();
}
}
}

Directoty 文件夹类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _01文件夹类
{
class Program
{
static void Main(string[] args)
{
//创建一个文件夹(目录),在指定的路径
Directory.CreateDirectory("新文件夹");
//如果想要删除该目录中所有的内容则采用这个方法的第二个重载,true即可
Directory.Delete("新文件夹");
Directory.Delete("新文件夹",true);
//判断该路径下是否有这个文件夹
Directory.Exists("新文件夹");
//获取该目录中所有文件的路径(包含文件名)
string[]path= Directory.GetFiles("新文件夹");
//获取该目录中所有的文本文件
string[]path= Directory.GetFiles("新文件夹","*.txt"); Console.ReadKey(); }
}
}

资料管理器(递归)

CS后台代码(源码附件在图片里)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace _03资料管理器
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//窗体加载事件
string path = "demo";
LoadDirectory(path,tv.Nodes);
}
private void LoadDirectory(string path, TreeNodeCollection tnc)
{
//加载所有的目录
string[] dires = Directory.GetDirectories(path);
for (int i = ; i < dires.Length; i++)
{
string name= Path.GetFileNameWithoutExtension(dires[i]);
TreeNode tn= tnc.Add(name);
//递归
LoadDirectory(dires[i],tn.Nodes);
}
//加载每个目录中的文件
string[]files= Directory.GetFiles(path);
for (int i = ; i < files.Length; i++)
{
string fileName= Path.GetFileNameWithoutExtension(files[i]);
TreeNode tn1= tnc.Add(fileName);
tn1.Tag = files[i];
//要想读取文件就要找到这个文件的路径
}
}
private void tv_DoubleClick(object sender, EventArgs e)
{
if (tv.SelectedNode.Tag!=null)
{
txt.Text= File.ReadAllText(tv.SelectedNode.Tag.ToString(),Encoding.Default);
}
} }
}

【基础巩固】文件流读写、大文件移动 FileStream StreamWriter File Path Directory/ ,m资料管理器(递归)

用户导出工具:

Export.ashx.cs

using DFS.Consumer.Cms.Sitecore_Modules.Shell.ExpUsers;
using DFS.Consumer.DataLayer;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization; namespace DFS.Consumer.Cms.Sitecore_Modules.Shell.UserExp
{
/// <summary>
/// Export 的摘要说明
/// </summary>
public class Export : IHttpHandler
{
string temp = string.Empty;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
Stopwatch watch = new Stopwatch();
watch.Start();
//CacheHelper.SetCache("tempvalue", System.DateTime.Now.ToShortTimeString());
var tab = context.Request["tab"].ToString();
switch (tab)
{
case "expcsv":
CacheHelper.SetCache("progressCount", "{'status':801,'msg':" + + "}");
int num = string.IsNullOrEmpty(context.Request.Form["num"].ToString()) ? : Convert.ToInt32(context.Request.Form["num"].ToString());
if (ButtonDownloadCsv_OnClick(num))
{ context.Response.Write("{'status':200,'msg':'complete'}");
CacheHelper.SetCache("progressCount", "{'status':700,'msg':" + + "}");
}
else
{
context.Response.Write("{'status':500,'msg':'Export fails, please contact your administrator'}");
}
MyLog("总用时:" + watch.Elapsed + "\r\n ----------------------------------------\n");
break;
case "getnum":
context.Response.Write(CacheHelper.GetCache("progressCount"));
//context.Response.Write("{'status':200,'msg':'" + CacheHelper.GetCache("progressCount") + "'}");
break;
case "expdb":
CacheHelper.SetCache("progressCount", "{'status':801,'msg':" + + "}");
int numdb = string.IsNullOrEmpty(context.Request.Form["num"].ToString()) ? : Convert.ToInt32(context.Request.Form["num"].ToString());
if (ButtonDownloadDB_OnClick(numdb))
{
context.Response.Write("{'status':200,'msg':'complete'}");
CacheHelper.SetCache("progressCount", "{'status':700,'msg':" + + "}");
}
else
{
context.Response.Write("{'status':500,'msg':'Export fails, please contact your administrator'}");
}
MyLog("总用时:" + watch.Elapsed + "\r\n ----------------------------------------\n");
break;
case "del":
if (ClearDB_OnClick())
{
context.Response.Write("{'status':200,'msg':'Completed!'}");
}
else
{
context.Response.Write("{'status':500,'msg':'failure!'}");
}
break;
case "download": if (File.Exists(WebConfigurationManager.AppSettings["ExpUserData"] + "DFS_User_Accounts.csv"))
{
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-disposition", "attachment;filename=DFS_User_Accounts.csv");
context.Response.WriteFile(WebConfigurationManager.AppSettings["ExpUserData"] + "DFS_User_Accounts.csv");
}
else
{
context.Response.Write("{'status':500,'msg':'no file!'}");
}
break;
case "downloadstatus": if (File.Exists(WebConfigurationManager.AppSettings["ExpUserData"] + "DFS_User_Accounts.csv"))
{
context.Response.Write("{'status':200,'msg':'exist'}");
}
else
{
context.Response.Write("{'status':500,'msg':'no file!'}");
} break;
case "getstatus":
if (CacheHelper.GetCache("progressCount")!=null)
{
int currentStatus = Convert.ToInt32(JObject.Parse(CacheHelper.GetCache("progressCount").ToString())["status"]);
if (currentStatus == || currentStatus == )
{
context.Response.Write("{'status':900,'msg':'Someone is exporting data to CSV, please wait until exportation is completed. Or you can click ‘Download CSV’ button to get last version of extraction data.'}");
break;
}
}
break;
}
} /// <summary>
/// 插入到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected bool ButtonDownloadDB_OnClick(int num)
{
Stopwatch sw_sql = new Stopwatch();
sw_sql.Start(); //MemberShip SqlHelper.CreateInstance("corelive").run //(new SqlCommand("SELECT * FROM dbo.aspnet_Membership"));//
Stopwatch watch_ship = new Stopwatch();
watch_ship.Start();
var list_mUser = GetListMemberShip();//GetActiveEmail();//
MyLog("GetListMemberShip:" + watch_ship.Elapsed + "\n");
Stopwatch watch_active = new Stopwatch();
watch_active.Start();
var list_Active = SqlHelper.CreateInstance("dfs").RunDynamicList("SELECT [Email] FROM [dbo].[CRMActivate]");
MyLog("是否激活用时:" + watch_active.Elapsed + "\n");
var builder = new StringBuilder();
//var streamWriter = new StreamWriter();
builder.AppendLine(@"""Account Name"",""Password"",""salt"",""Title"",""First Name"",""Surname"",""Country"",""Email"",""Gender"",""Address"",""Primary Area Code"",""Primary Contact Number"",""Secondary Area Code"",""Secondary Contact Number"",""Age Range"",""Preferred Language"",""Social Type"",""Social ID"",""Receive Newsletter"",""Receive Member Updates"",""Preferred DFS Location"",""Register Location"",""Register Language"",""ID"",""Social Email"",""Loyal T Number"",""Active Or Not"",""Register Date"",""Last Login Date"",""First Name On Passport"",""Last Name On Passport"",""Passport Number"",""Date Of Birth"",""Prefered Method Of Contact""");
var listtemp = GetUserList(num, );
int progressCount = ;
Stopwatch watch_sql = new Stopwatch();
watch_sql.Start();
var sb = new StringBuilder();
foreach (var user in listtemp)
{ if (progressCount % == )
{
CacheHelper.SetCache("progressCount", "{'status':200,'msg':" + progressCount + "}");//progressCount);
//progress.Text += System.DateTime.Now.ToShortTimeString() + ":" + "已导出数据:" + progressCount + "条\n";
} var usertemp = list_mUser.Where(o => o.UserId == user.ID).FirstOrDefault();
var password = string.Empty;
var passwordSalt = string.Empty;
if (list_mUser.Where(o => o.UserId == user.ID).FirstOrDefault() != null)
{
password = usertemp.Password;
passwordSalt = usertemp.PasswordSalt; }
else
{
continue;
}
sb.Append(string.Format(@"
INSERT INTO [UserExp].[dbo].[UserInfo]
([AccountName]
,[Password]
,[Salt]
,[Title]
,[FirstName]
,[Surname]
,[Country]
,[Email]
,[Gender]
,[Address]
,[PrimaryAreaCode]
,[PrimaryContactNumber]
,[SecondaryAreaCode]
,[SecondaryContactNumber]
,[AgeRange]
,[PreferredLanguage]
,[SocialType]
,[SocialID]
,[ReceiveNewsletter]
,[ReceiveMemberUpdates]
,[PreferredDFSLocation]
,[RegisterLocation]
,[RegisterLanguage]
,[ID]
,[SocialEmail]
,[LoyalTNumber]
,[ActiveOrNot]
,[RegisterDate]
,[LastLoginDate]
,[FirstNameOnPassport]
,[LastNameOnPassport]
,[PassportNumber]
,[DateOfBirth]
,[PreferedMethodOfContact])
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}','{26}','{27}','{28}','{29}','{30}','{31}','{32}','{33}');",
HttpUtility.UrlEncode(user.AccountName),//解码:System.Web.HttpUtility.UrlDecode(s);
password,
passwordSalt,
HttpUtility.UrlEncode(user.UserTitle),
HttpUtility.UrlEncode(user.FirstName),
HttpUtility.UrlEncode(user.Surname),
HttpUtility.UrlEncode(user.Country),
HttpUtility.UrlEncode(user.Email),
HttpUtility.UrlEncode(user.Gender),
HttpUtility.UrlEncode(user.Address),
user.PrimaryAreaCode,//"Primary Area Code"),
user.PrimaryContactNumber,
user.SecondaryAreaCode,//"Secondary Area Code"),
user.SecondaryContactNumber,
HttpUtility.UrlEncode(user.AgeRange),
HttpUtility.UrlEncode(user.PreferredLanguage),
HttpUtility.UrlEncode(user.SocialType),
user.SocialID,
user.ReceiveNewsletter == "Yes" ? : ,//"Receive Newsletter"),
user.ReceiveMemberUpdates == "Yes" ? : ,//"Receive Member Updates"),
HttpUtility.UrlEncode(user.PreferredDFSLocation),//"Preferred DFS Location"),
HttpUtility.UrlEncode(user.RegLocation),
HttpUtility.UrlEncode(user.RegLanguage),
user.ID,
HttpUtility.UrlEncode(user.SocialEmail),
HttpUtility.UrlEncode(user.LoyalTNumber),
list_Active.Where(o => o.Email == user.Email).Count() > ? : ,
user.RegisterDate.ToString(),
user.LastLoginDate.ToString(),
HttpUtility.UrlEncode(user.FirstNameonPassport),//"First Name On Passport"),
HttpUtility.UrlEncode(user.LastNameonPassport),//"Last Name On Passport"),
user.PassportNumber,//"assport Number"),
user.DateOfBirth,
HttpUtility.UrlEncode(user.PreferredMethodofContact)));
progressCount++;
} MyLog("拼接SQL用时:" + watch_sql.Elapsed + "\r\n共:" + progressCount + "条");
Stopwatch watch_io = new Stopwatch();
watch_io.Start();
var cmd = new SqlCommand(sb.ToString());
SqlHelper.CreateInstance("userexp").RunNoneQuery(cmd);
MyLog("执行SQL:" + watch_io.Elapsed + "\n");
return true;
}
/// <summary>
/// 清空数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected bool ClearDB_OnClick()
{ var helper = SqlHelper.CreateInstance("userexp");
const string insertQuery = @"delete UserInfo where 1=1;";
var cmd = new SqlCommand(insertQuery);
helper.RunNoneQuery(cmd);
return true; } /// <summary>
/// 插入到CSV 3.5万条1分钟左右
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected bool ButtonDownloadCsv_OnClick(int num)
{
//MemberShip SqlHelper.CreateInstance("corelive").run //(new SqlCommand("SELECT * FROM dbo.aspnet_Membership"));//
Stopwatch watch_ship = new Stopwatch();
watch_ship.Start();
var list_mUser = GetListMemberShip();//GetActiveEmail();//
MyLog("GetListMemberShip:" + watch_ship.Elapsed + "\n");
Stopwatch watch_active = new Stopwatch();
watch_active.Start();
var list_Active = SqlHelper.CreateInstance("dfs").RunDynamicList("SELECT [Email],[LoyalTNo] FROM [dbo].[CRMActivate]");
MyLog("是否激活用时:" + watch_active.Elapsed + "\n");
var builder = new StringBuilder();
//var streamWriter = new StreamWriter();
builder.AppendLine(@"""Account Name"",""Password"",""salt"",""Title"",""First Name"",""Surname"",""Country"",""Email"",""Gender"",""Address"",""Primary Area Code"",""Primary Contact Number"",""Secondary Area Code"",""Secondary Contact Number"",""Age Range"",""Preferred Language"",""Social Type"",""Social ID"",""Receive Newsletter"",""Receive Member Updates"",""Preferred DFS Location"",""Register Location"",""Register Language"",""ID"",""Social Email"",""Loyal T Number"",""Active Or Not"",""Register Date"",""Last Login Date"",""First Name On Passport"",""Last Name On Passport"",""Passport Number"",""Date Of Birth"",""Prefered Method Of Contact""");
var listtemp = GetUserList(num, );
int progressCount = ;
Stopwatch watch_sql = new Stopwatch();
watch_sql.Start();
foreach (var user in listtemp)
{
if (progressCount % == )
{
CacheHelper.SetCache("progressCount", "{'status':200,'msg':" + progressCount + "}");//progressCount);
//progress.Text += System.DateTime.Now.ToShortTimeString() + ":" + "已导出数据:" + progressCount + "条\n";
} if (string.IsNullOrEmpty(user.ID) || user.AccountName.StartsWith("sitecore"))
{
continue;
}
var usertemp = list_mUser.Where(o => o.UserId == user.ID).FirstOrDefault();
var password = string.Empty;
var passwordSalt = string.Empty;
if (list_mUser.Where(o => o.UserId == user.ID).FirstOrDefault() != null)
{
password = usertemp.Password;
passwordSalt = usertemp.PasswordSalt; }
//if (list_Active.Where(o=>o.Email==user.Email).FirstOrDefault()==null)
//{
// continue;
//}
//MyLog(list_mUser.Where(o => o.UserId == user.ID).FirstOrDefault().Password); //password = String.Format(list_mUser.Where(o => o.UserId == new Guid(user.ID)).FirstOrDefault().Password);
// password=string.IsNullOrEmpty( list_mUser.Where(o => o.UserId == new Guid(user.ID)).FirstOrDefault().Password)?"",list_mUser.Where(o => o.UserId == new Guid(user.ID)).FirstOrDefault().Password;
if (!DFS.Consumer.Security.UserManager.IsEmail(user.Email))
continue;
var fullName = ContainsChinese(user.Surname + user.FirstName)
? user.Surname + user.FirstName
: user.FirstName + " " + user.Surname;
builder.AppendLine(string.Format(@"""{0}"",""{1}"",""{2}"",""{3}"",""{4}"",""{5}"",""{6}"",""{7}"",""{8}"",""{9}"",""{10}"",""{11}"",""{12}"",""{13}"",""{14}"",""{15}"",""{16}"",""{17}"",""{18}"",""{19}"",""{20}"",""{21}"",""{22}"",""{23}"",""{24}"",""{25}"",""{26}"",""{27}"",""{28}"",""{29}"",""{30}"",""{31}"",""{32}"",""{33}""",
user.AccountName,
password,//DFSConsumer_CoreLive].[dbo].[aspnet_Membership] 根据ID可以获取
passwordSalt,
user.UserTitle.Replace("\"", ""),
user.FirstName.Replace("\"", ""),
user.Surname.Replace("\"", ""),
user.Country.Replace("\"", ""),
user.Email.Replace("\"", ""),
user.Gender.Replace("\"", ""),
user.Address.Replace("\"", ""),
user.PrimaryAreaCode.Replace("\"", ""),//"Primary Area Code",
user.PrimaryContactNumber.Replace("\"", ""),
user.SecondaryAreaCode.Replace("\"", ""), //"Secondary Area Code",
user.SecondaryContactNumber.Replace("\"", ""),
user.AgeRange.Replace("\"", ""),
user.PreferredLanguage.Replace("\"", ""),
user.SocialType.Replace("\"", ""),
user.SocialID.Replace("\"", ""),
user.ReceiveNewsletter.Replace("\"", ""),//"Receive Newsletter",
user.RecMemberUpdate.Replace("\"", ""),//"Receive Member Updates",
user.PreferredDFSLocation.Replace("\"", ""), //"Preferred DFS Location",
user.RegLocation.Replace("\"", ""),
user.RegLanguage.Replace("\"", ""),
user.ID.Replace("\"", ""),
user.SocialEmail.Replace("\"", ""),
list_Active.Where(o => o.Email == user.Email).FirstOrDefault()!=null?list_Active.Where(o => o.Email == user.Email).FirstOrDefault().LoyalTNo:"",//user.LoyalTNumber.Replace("\"", ""),
list_Active.Where(o => o.Email == user.Email).Count() > ? "Yes" : "No",//user.Email).FirstOrDefault().Email,//Count()>0 ? "Yes" : "No",//"Active Or Not",// [DFSConsumer_DFS].[dbo].[CRMActivate]
user.RegisterDate,
user.LastLoginDate,
user.FirstNameonPassport.Replace("\"", ""),//"First Name On Passport",
user.LastNameonPassport.Replace("\"", ""),//"Last Name On Passport",
user.PassportNumber.Replace("\"", ""),//"assport Number",
user.DateOfBirth.Replace("\"", ""),//"Date Of Birth",
user.PreferredMethodofContact.Replace("\"", "")));//"Prefered Method Of Contact"));
progressCount++;
} MyLog("创建表格用时:" + watch_sql.Elapsed + "\r\n共:" + progressCount + "条");
Stopwatch watch_io = new Stopwatch();
watch_io.Start();
using (StreamWriter streamWriter = new StreamWriter(WebConfigurationManager.AppSettings["ExpUserData"] + "DFS_User_Accounts.csv", false, Encoding.GetEncoding("UTF-8"))) //GB2312
{
streamWriter.Write(builder.ToString());
}
MyLog("写入流用时:" + watch_io.Elapsed + "\n");
return true;
} #region tool private static bool ContainsChinese(string src)
{
var reg = new System.Text.RegularExpressions.Regex(@"[\u4e00-\u9fbf]{1,}");
return reg.IsMatch(src);
} private List<MemberShip> GetListMemberShip()
{
List<MemberShip> list_mUser = new List<MemberShip>();
var tb_mUser = DFS.Consumer.DataLayer.SqlHelper.CreateInstance("corelive").RunSelectQuery(new SqlCommand("SELECT * FROM dbo.aspnet_Membership"));
//var list_Active = SqlHelper.CreateInstance("dfs").RunDynamicList("SELECT [Email] FROM [dbo].[CRMActivate]");
//foreach (var item in lis_Active)
//{
// MyLog(item.Email);
//}
foreach (DataRow dr in tb_mUser.Rows)
{
list_mUser.Add(new MemberShip
{
Password = dr["Password"].ToString(),
UserId = string.IsNullOrEmpty(dr["UserId"].ToString()) ? "" : dr["UserId"].ToString(),
PasswordSalt = dr["PasswordSalt"].ToString()
//ActiveOrNot=list_Active.Contains("")?"":""
}); //MyLog(dr["Password"].ToString() + " | " + dr["UserId"].ToString() + " | " + dr["PasswordSalt"].ToString());
} return list_mUser;
}
/// <summary>
/// 获取用户列表 分页
/// </summary>
/// <param name="pageSize"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
private List<UserInfo> GetUserList(int pageSize, int pageIndex)
{
var userInfoList = new List<UserInfo>();
Stopwatch watch1 = new Stopwatch();
watch1.Start(); var users = Sitecore.Security.Accounts.RolesInRolesManager.GetUsersInRole(Sitecore.Security.Accounts.Role.FromName("dfs\\Business User"), false); users = pageSize > ? users.Take(pageSize) : users; MyLog("Sitecore查询用时:" + watch1.Elapsed + "\n");
Stopwatch watch2 = new Stopwatch();
watch2.Start();
var businessUserRole = DFS.Consumer.Security.UserRoles.BusinessUserRole;
userInfoList = businessUserRole == null || users == null
? new List<UserInfo>()
: (from user in users
let membershipUser = System.Web.Security.Membership.GetUser(user.Profile.UserName)
where membershipUser != null && !membershipUser.IsLockedOut
where !string.IsNullOrEmpty(user.Profile.UserName)
&& !string.IsNullOrEmpty(user.Profile.Email)
&& user.Profile.Comment != "Disabled"
select UserInfo.Get(user)).ToList();
MyLog("linq查询用时:" + watch2.Elapsed + "\n");
return userInfoList; }
/// <summary>
/// 写日志
/// </summary>
/// <param name="msg"></param>
private void MyLog(string msg)
{
//using (FileStream fs = new FileStream("c:/test/log.txt", FileMode.Create, FileAccess.Write))
//{
// //string msg = "总用时:" + watch.Elapsed + "\n";
// byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
// fs.Write(buffer, 0, buffer.Length); //}
try
{
using (FileStream fs = new FileStream(WebConfigurationManager.AppSettings["ExpUserData"] + "log.txt", FileMode.Append, FileAccess.Write))
{
msg = "\r\n" + System.DateTime.Now.ToString() + ":\r\n" + msg;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
fs.Write(buffer, , buffer.Length);
}
}
catch (Exception e)
{ MyLog(e.Message.ToString());
}
}
#endregion public bool IsReusable
{
get
{
return false;
}
}
}
}
                using (FileStream fs = new FileStream(ConfigurationManager.AppSettings["LogDirectory"] + DateTime.Now.ToString("yyyy-MM-dd") + "log.txt", FileMode.Append, FileAccess.Write))
{
//msg = "\r\n" + System.DateTime.Now.ToString() + ":\r\n" + msg;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);
fs.Write(buffer, , buffer.Length);
}
 <add key="LogDirectory" value="E:\inetpub\wwwroot\authoring1.dfs.com\Data\ServiceLog\Flight\"/>

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DFS.Consumer.Cms.Sitecore_Modules.Shell.ExpUsers.Default" %>

<!DOCTYPE html>

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="Resources/DFS-favicon.ico"> <title>User Extraction</title> <!-- Bootstrap core CSS -->
<link href="./Resources/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template -->
<link href="./Resources/dashboard.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE ]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="./Resources/ie-emulation-modes-warning.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE ]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.0/html5shiv.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head> <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">User Extraction</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="JavaScript:;">User Extraction</a>
</div>
<%-- <div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="JavaScript:;">Dashboard</a></li>
<li><a href="JavaScript:;">Settings</a></li>
<li><a href="JavaScript:;">Profile</a></li>
<li><a href="JavaScript:;">Help</a></li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search...">
</form>
</div>--%>
</div>
</nav> <div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li class="active"><a href="JavaScript:;">Export Users</a></li>
<!--<li><a href="http://v3.bootcss.com/examples/dashboard/#">Reports</a></li>
<li><a href="http://v3.bootcss.com/examples/dashboard/#">Analytics</a></li>
<li><a href="http://v3.bootcss.com/examples/dashboard/#">Export</a></li>-->
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <%-- <form id="form2" runat="server">--%>
<button class="btn btn-primary" id="expcsv">Export To CSV</button>
<button class="btn btn-primary" id="downloadcsv">Download CSV</button>
<%-- <button class="btn btn-primary" id="expdb">Export To DataBase</button>
<button class="btn btn-danger" id="cleardb">Clear DataBase</button>--%>
<%--<asp:Button ID="ButtonDownloadCsv" runat="server" Text="Export To CSV" OnClick="ButtonDownloadCsv_OnClick" CssClass="btn btn-primary" />
<asp:Button ID="ButtonDownloadDB" runat="server" Text="Export To DataBase" OnClick="ButtonDownloadDB_OnClick" CssClass="btn btn-primary" />
<asp:Button ID="ClearDB" runat="server" Text="Clear DataBase" OnClick="ClearDB_OnClick" CssClass="btn btn-danger" /><br />--%>
<br />
<%-- Export Quantity( or not input is all):--%> <input id="num" placeholder="Number" class="form-control" style="display: none" value="" />
<%--<asp:TextBox ID="TextBox1" runat="server" CssClass="form-control"></asp:TextBox>--%>
<br />
<%--<p style="color: red">View the data path C:\inetpub\wwwroot\DFS\Data\UserExp\</p>--%>
<div>
<h3>Export the progress:</h3>
<%-- <asp:Label ID="progress" runat="server" Text=""></asp:Label>
<p id=""></p>--%>
<div id="proinfo"></div>
</div>
<div style="display: none" class="table-responsive">
<table class="table table-striped">
<thead>
<tr> <th>Account Name</th>
<th>UserTitle</th>
<th>FirstName</th>
<th>Surname</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<%-- <%foreach (var item in UserInfoList10)
{
%>
<tr>
<td><%=item.AccountName %></td>
<td><%=item.UserTitle %></td>
<td><%=item.FirstName %></td>
<td><%=item.Surname %></td>
<td><%=item.Country %></td>
</tr> <%} %>--%>
</tbody>
</table>
<%-- 总条数:<%=UserCount %>--%>
</div>
<%--</form>--%>
</div>
</div>
</div> <!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="./Resources/jquery.min.js"></script>
<script src="./Resources/bootstrap.min.js"></script>
<script src="./Resources/docs.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows bug -->
<script src="./Resources/ie10-viewport-bug-workaround.js"></script> <div id="global-zeroclipboard-html-bridge" class="global-zeroclipboard-container" title="" style="position: absolute; left: 0px; top: -9999px; width: 15px; height: 15px; z-index: 999999999;" data-original-title="Copy to clipboard">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="global-zeroclipboard-flash-bridge" width="100%" height="100%">
<param name="movie" value="/assets/flash/ZeroClipboard.swf?noCache=1479180476023">
<param name="allowScriptAccess" value="sameDomain">
<param name="scale" value="exactfit">
<param name="loop" value="false">
<param name="menu" value="false">
<param name="quality" value="best">
<param name="bgcolor" value="#ffffff">
<param name="wmode" value="transparent">
<param name="flashvars" value="trustedOrigins=v3.bootcss.com%2C%2F%2Fv3.bootcss.com%2Chttp%3A%2F%2Fv3.bootcss.com">
<embed src="/assets/flash/ZeroClipboard.swf?noCache=1479180476023" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="100%" height="100%" name="global-zeroclipboard-flash-bridge" allowscriptaccess="sameDomain" allowfullscreen="false" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="trustedOrigins=v3.bootcss.com%2C%2F%2Fv3.bootcss.com%2Chttp%3A%2F%2Fv3.bootcss.com" scale="exactfit">
</object>
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="" height="" viewBox="0 0 200 200" preserveAspectRatio="none" style="visibility: hidden; position: absolute; top: -100%; left: -100%;">
<defs></defs><text x="" y="" style="font-weight: bold; font-size: 10pt; font-family: Arial, Helvetica, Open Sans, sans-serif; dominant-baseline: middle">200x200</text>
</svg>
<script type="text/javascript">
//下载csv download
$('#downloadcsv').click(function () {
//location.href = 'Export.ashx?tab=download'
$.post("Export.ashx", { tab: "downloadstatus" }, function (result) {
if (result != null && result != "" && result != undefined) {
var rejson = eval('(' + result + ')');
if (rejson.status == ) {
location.href = 'Export.ashx?tab=download';
//window.clearInterval(intv);
} else {
alert(rejson.msg);
}
} else { location.href = 'Export.ashx?tab=download';
} });
// $("#proinfo").html(getNowFormatDate() + infoHtml);
});
var temp = ;
//导出CSV
$('#expcsv').click(function () { $.post("Export.ashx", { tab: "getstatus" }, function (result) {
if (result != null && result != "" && result != undefined) {
var rejson = eval('(' + result + ')');
if (rejson.status == ) {
//window.clearInterval(intv);
alert(rejson.msg);
} else {
startExp();
}
} else {
startExp();
} }); //$("#proinfo").html("<p>" + getNowFormatDate() + ":Started"); }); function startExp() {
alert("start");//Started'
$("#expcsv").attr("disabled", true);
$("#downloadcsv").attr("disabled", true);
setintv();
$.post("Export.ashx", { tab: "expcsv", num: $("#num").val() }, function (result) {
var rejson = eval('(' + result + ')');
$("#expcsv").attr("disabled", false);
$("#downloadcsv").attr("disabled", false);
if (rejson.status != ) {
window.clearInterval(intv);
alert(rejson.msg);
return;
}
}); $("#proinfo").html("<p>" + getNowFormatDate() + ":Started");
}
////导出db
//$('#expdb').click(function () {
// //alert("start");
// //$.post("Export.ashx", { tab: "expdb" }, function (result) {
// alert("start");//Started'
// //$("#proinfo").html("<p>" + getNowFormatDate() + ":Started");
// $.post("Export.ashx", { tab: "expdb", num: $("#num").val() }, function (result) {
// var rejson = eval('(' + result + ')');
// if (rejson.status == 200) {
// //alert(rejson.msg);
// }
// });
// setintv();
// $("#proinfo").html("<p>" + getNowFormatDate() + ":Started");
//});
////清空数据库
//$('#cleardb').click(function () {
// if (confirm("Sure to delete?")) {
// $.post("Export.ashx", { tab: "del" }, function (result) {
// var rejson = eval('(' + result + ')');
// if (rejson.status == 200) {
// alert(rejson.msg);
// }
// });
// }
//}); var infoHtml = "<p>" + getNowFormatDate() + ":Started";
var tempCount = ;//已导出数量
var counter = ;//循环秒数
//var completed = 0;//表及输入完成次数
function setintv() {
var intv = setInterval(function (event) {
$.post("Export.ashx", { tab: "getnum", num: $("#num").val() }, function (result) {
if (result != null && result != "" && result != undefined) { var rejson = eval('(' + result + ')'); //eval(result); switch (rejson.status) {
case :
if (tempCount != rejson.msg && rejson.msg > ) {
infoHtml = "<p>" + getNowFormatDate() + ":Exported " + rejson.msg + " data</p>" + $("#proinfo").html();
tempCount = rejson.msg;
}
break;
case :
if (counter >= ) {
infoHtml = "<p>" + getNowFormatDate() + ":Data being queried, please wait a moment.</p>" + $("#proinfo").html();
counter = ;
} else {
counter++;
}
break
case :
//alert("进入700");
//if (completed == 0) {
infoHtml = "<p>" + getNowFormatDate() + ":Completed!</p>" + $("#proinfo").html();
//completed++;
window.clearInterval(intv);
// } break;
} $("#proinfo").html(infoHtml);
}
});
}, );
} function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + ;
var strDate = date.getDate();
if (month >= && month <= ) {
month = "" + month;
}
if (strDate >= && strDate <= ) {
strDate = "" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
</script>
</body>
</html>

调试写日志

            //bool append = true;
System.IO.TextWriter textWriter = new System.IO.StreamWriter("c://test002.log",true);
textWriter.Write("\n这是测试写文件002");
textWriter.Close();

读取文件

        public void MyLog(string msg)
{
System.IO.TextWriter textWriter = new System.IO.StreamWriter("mylog.log", true);//这个不是网站根目录,可能是运行时根目录
msg = "\r\n" + System.DateTime.Now.ToString() + ":\r\n" + msg;
textWriter.Write(msg + "\nm");
textWriter.Close();
}
            System.IO.StreamReader reader = new System.IO.StreamReader("c://test002.log");
string contents = reader.ReadToEnd();
reader.Close();
Console.Write(contents);
Console.Read();
上一篇:Maven生命周期


下一篇:02-大文件Copy(FileStream文件流类)