【基础巩固】文件流读写、大文件移动 FileStream StreamWriter File Path Directory/ ,m资料管理器(递归)...
生活随笔
收集整理的這篇文章主要介紹了
【基础巩固】文件流读写、大文件移动 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 可讀可寫 大文件 釋放
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, 0, buffer.Length);string msg = System.Text.Encoding.UTF8.GetString(buffer);Console.WriteLine(msg);}Console.ReadKey();}} } View Code?
大文件移動
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)){//每次讀取的大小是5Mbyte[]buffer=new byte[1024*1024*5];//實際(真正讀取到的大小)int r= fsRead.Read(buffer, 0, buffer.Length);while (r>0){//寫入fsWrite.Write(buffer, 0, r);Console.WriteLine("**");//再讀取r = fsRead.Read(buffer, 0, buffer.Length);}}}Console.WriteLine("ok了");Console.ReadKey();}} } View Code?
另一種方式的讀寫
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(); }} } View Code?
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(); View Code?
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();}} } View Code?
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();}} } View Code?
資料管理器(遞歸)
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 = 0; 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 = 0; 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);}}} } View Code用戶導出工具:
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':" + 0 + "}");int num = string.IsNullOrEmpty(context.Request.Form["num"].ToString()) ? 0 : Convert.ToInt32(context.Request.Form["num"].ToString());if (ButtonDownloadCsv_OnClick(num)){context.Response.Write("{'status':200,'msg':'complete'}");CacheHelper.SetCache("progressCount", "{'status':700,'msg':" + 0 + "}");}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':" + 0 + "}");int numdb = string.IsNullOrEmpty(context.Request.Form["num"].ToString()) ? 0 : Convert.ToInt32(context.Request.Form["num"].ToString());if (ButtonDownloadDB_OnClick(numdb)){context.Response.Write("{'status':200,'msg':'complete'}");CacheHelper.SetCache("progressCount", "{'status':700,'msg':" + 0 + "}");}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 == 801 || currentStatus == 200){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, 1);int progressCount = 0;Stopwatch watch_sql = new Stopwatch();watch_sql.Start();var sb = new StringBuilder();foreach (var user in listtemp){if (progressCount % 5000 == 0){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" ? 1 : 0,//"Receive Newsletter"),user.ReceiveMemberUpdates == "Yes" ? 1 : 0,//"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() > 0 ? 1 : 0,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, 1);int progressCount = 0;Stopwatch watch_sql = new Stopwatch();watch_sql.Start();foreach (var user in listtemp){if (progressCount % 5000 == 0){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() > 0 ? "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 toolprivate 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 > 0 ? 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 userslet membershipUser = System.Web.Security.Membership.GetUser(user.Profile.UserName)where membershipUser != null && !membershipUser.IsLockedOutwhere !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, 0, buffer.Length);}}catch (Exception e){MyLog(e.Message.ToString());}}#endregionpublic bool IsReusable{get{return false;}}} } View Code 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, 0, buffer.Length);} View Code <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 9]><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 9]><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(0 or not input is all):--%><input id="num" placeholder="Number" class="form-control" style="display: none" value="999999" /><%--<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 8 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="200" height="200" viewBox="0 0 200 200" preserveAspectRatio="none" style="visibility: hidden; position: absolute; top: -100%; left: -100%;"><defs></defs><text x="0" y="10" 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 == 200) {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 = 0;//導出CSV$('#expcsv').click(function () {$.post("Export.ashx", { tab: "getstatus" }, function (result) {if (result != null && result != "" && result != undefined) {var rejson = eval('(' + result + ')');if (rejson.status == 900) {//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 != 200) {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 = 0;//已導出數量var counter = 0;//循環秒數//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 200:if (tempCount != rejson.msg && rejson.msg > 0) {infoHtml = "<p>" + getNowFormatDate() + ":Exported " + rejson.msg + " data</p>" + $("#proinfo").html();tempCount = rejson.msg;}break;case 801:if (counter >= 20) {infoHtml = "<p>" + getNowFormatDate() + ":Data being queried, please wait a moment.</p>" + $("#proinfo").html();counter = 0;} else {counter++;}breakcase 700://alert("進入700");//if (completed == 0) {infoHtml = "<p>" + getNowFormatDate() + ":Completed!</p>" + $("#proinfo").html();//completed++; window.clearInterval(intv);// }break;}$("#proinfo").html(infoHtml);}});}, 1000);}function getNowFormatDate() {var date = new Date();var seperator1 = "-";var seperator2 = ":";var month = date.getMonth() + 1;var strDate = date.getDate();if (month >= 1 && month <= 9) {month = "0" + month;}if (strDate >= 0 && strDate <= 9) {strDate = "0" + strDate;}var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate+ " " + date.getHours() + seperator2 + date.getMinutes()+ seperator2 + date.getSeconds();return currentdate;}</script> </body> </html> View Code?調試寫日志
//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();?
轉載于:https://www.cnblogs.com/xiaoshi657/p/5243647.html
總結
以上是生活随笔為你收集整理的【基础巩固】文件流读写、大文件移动 FileStream StreamWriter File Path Directory/ ,m资料管理器(递归)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中跳转到系统设置界面
- 下一篇: ME525 刷机历险记