【基础巩固】文件流读写、大文件移动 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资料管理器(递归)..._第1张图片

 

文件流
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))
                {
                    //每次读取的大小是5M
                    byte[]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

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

用户导出工具:

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
{
    /// 
    /// Export 的摘要说明
    /// 
    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;
            }
        }

        /// 
        /// 插入到数据库
        /// 
        /// 
        /// 
        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;
        }
        /// 
        /// 清空数据库
        /// 
        /// 
        /// 
        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;

        }

        /// 
        /// 插入到CSV 3.5万条1分钟左右
        /// 
        /// 
        /// 
        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 tool


        private static bool ContainsChinese(string src)
        {
            var reg = new System.Text.RegularExpressions.Regex(@"[\u4e00-\u9fbf]{1,}");
            return reg.IsMatch(src);
        }

        private List GetListMemberShip()
        {
            List list_mUser = new List();
            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;
        }
        /// 
        /// 获取用户列表 分页
        /// 
        /// 
        /// 
        /// 
        private List GetUserList(int pageSize, int pageIndex)
        {
            var userInfoList = new List();
            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()
                : (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;

        }
        /// 
        /// 写日志
        /// 
        /// 
        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());
            }
        }
        #endregion


        public 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" %>




"en">

    "Content-Type" content="text/html; charset=UTF-8">

    "X-UA-Compatible" content="IE=edge">
    "viewport" content="width=device-width, initial-scale=1">
    "description" content="">
    "author" content="">
    "icon" href="Resources/DFS-favicon.ico">

    User Extraction

    
    "./Resources/bootstrap.min.css" rel="stylesheet">

    
    "./Resources/dashboard.css" rel="stylesheet">

    
    
    

    
    




    

    
class="container-fluid">
class="row">
class="col-sm-3 col-md-2 sidebar">
class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <%--
"form2" runat="server">--%> <%-- --%> <%--"ButtonDownloadCsv" runat="server" Text="Export To CSV" OnClick="ButtonDownloadCsv_OnClick" CssClass="btn btn-primary" /> "ButtonDownloadDB" runat="server" Text="Export To DataBase" OnClick="ButtonDownloadDB_OnClick" CssClass="btn btn-primary" /> "ClearDB" runat="server" Text="Clear DataBase" OnClick="ClearDB_OnClick" CssClass="btn btn-danger" />
--%>
<%-- Export Quantity(0 or not input is all):--%> "num" placeholder="Number" class="form-control" style="display: none" value="999999" /> <%--"TextBox1" runat="server" CssClass="form-control">--%>
<%--

"color: red">View the data path C:\inetpub\wwwroot\DFS\Data\UserExp\

--%>

Export the progress:

<%-- "progress" runat="server" Text="">

"">

--%>
"proinfo">
"display: none" class="table-responsive"> class="table table-striped"> <%-- <%foreach (var item in UserInfoList10) { %> <%} %>--%>
Account Name UserTitle FirstName Surname Country
<%=item.AccountName %> <%=item.UserTitle %> <%=item.FirstName %> <%=item.Surname %> <%=item.Country %>
<%-- 总条数:<%=UserCount %>--%>
<%----%>
"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%"> "movie" value="/assets/flash/ZeroClipboard.swf?noCache=1479180476023"> "allowScriptAccess" value="sameDomain"> "scale" value="exactfit"> "loop" value="false"> "menu" value="false"> "quality" value="best"> "bgcolor" value="#ffffff"> "wmode" value="transparent"> "flashvars" value="trustedOrigins=v3.bootcss.com%2C%2F%2Fv3.bootcss.com%2Chttp%3A%2F%2Fv3.bootcss.com"> "/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>
"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%;"> "0" y="10" style="font-weight: bold; font-size: 10pt; font-family: Arial, Helvetica, Open Sans, sans-serif; dominant-baseline: middle">200x200
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资料管理器(递归)...)