2.0将EXCEL文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)
string fileName = "text.txt"; if (!File.Exists(fileName))//判断文件是否存在 { File.Create(fileName);//创建一个文本文件 } //判断文件夹是否已经具有隐藏属性 if ((File.GetAttributes(fileName)&FileAttributes.Hidden)!=FileAttributes.Hidden) { File.SetAttributes(fileName, FileAttributes.Hidden);//将文本文件隐藏属性开启 }
string directoryName = "test"; if (!Directory.Exists(directoryName))//判断文件夹是否存在 { Directory.CreateDirectory(directoryName);//创建文件夹 } //获取文件夹访问控制列表 DirectorySecurity dirSecurity = Directory.GetAccessControl(directoryName); //将指定访问控制列表添加到当前文件夹 dirSecurity.AddAccessRule(new FileSystemAccessRule("Admin", FileSystemRights.Read, InheritanceFlags.None, PropagationFlags.InheritOnly, AccessControlType.Allow));//这里的 Admin 字符串是 系统的用户名,否则会报错 Directory.SetAccessControl(directoryName, dirSecurity);//设置文件夹访问控制列表
1.0与1.1 比较
不同之处: 一个是文件一个是文件夹,所以在判断文件和文件夹是否存在的时候 用的类不同 ,分别是File 和 Directory
下面对这两个类给个初步说明
File :提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 System.IO.FileStream 对象。
Directory:公开用于创建、移动和枚举通过目录和子目录的静态方法。 此类不能被继承。
处理文件会经常使用这2个类
static void Main(string[] args) { string path = @"D:\study\2015年\文件系统\01\01"; DisplayDirectories(path); } static void DisplayDirectories(string path) { DirectoryInfo directoryInfo = new DirectoryInfo(path); Console.WriteLine(directoryInfo.FullName);//输出文件夹信息 foreach (DirectoryInfo DI in directoryInfo.GetDirectories()) { DisplayDirectories(DI.FullName);//输出子文件夹信息 } }
这里介绍下 DirectoryInfo 类 :公开用于创建、移动和枚举目录和子目录的实例方法。 此类不能被继承。
static void Main(string[] args) { string path = @"D:\study\2015年\文件系统\01\01"; Console.WriteLine("路径{0}下的文件数目为{1}", path, GetFileCount(path)); } static int GetFileCount(string path) { int count = 0; //文件数目 DirectoryInfo directoryInfo = new DirectoryInfo(path);//路径信息 count += directoryInfo.GetFiles().Length; foreach (var item in directoryInfo.GetDirectories())//获取路劲下的子目录 { count += GetFileCount(item.FullName);//获取子目录中的文件数目 } return count; }
//先创建文件 Random random = new Random(); string path = Directory.GetCurrentDirectory();//获取当前路径创建10个随机命名的文件 for (int i = 0; i < 10; i++) { File.CreateText(path + "\\" + random.Next(int.MaxValue) + ".txt").Close(); } DirectoryInfo directoryInfo = new DirectoryInfo(path);//创建当前目录信息类实例 Console.WriteLine("当前目录下的文本文件有:"); foreach (FileInfo file in directoryInfo.GetFiles("*.txt")) { Console.WriteLine(file.Name); } //对文件重命名 Console.WriteLine("对当前目录下的文本文件重命名:"); foreach (FileInfo file in directoryInfo.GetFiles("*.txt")) { string newName = random.Next(int.MaxValue).ToString(); Console.WriteLine("将{0}重命名为{1}", file.Name, newName + ".txt"); File.Move(file.Name, newName + ".txt"); }
//创建文本文件 string fileName = Directory.GetCurrentDirectory() + "\\zhiniao.txt"; StreamWriter writer = File.CreateText(fileName);//创建文本文件写入流类实例 for (int i = 0; i < 100; i++) { writer.Write("zhiniao ");//**这里有个小异常没有解决,望有心人看见给予帮助? } writer.Close(); //以文件流的形式打开 zhiniao.txt, 将其按指定大小分割 FileStream fileStream = new FileStream(fileName, FileMode.Open);//创建文件流类型 Console.WriteLine("文件{0}的长度为{1}字节", fileStream.Name, fileStream.Length); Console.WriteLine("请输入需要分割文件的长度:"); int subLength = int.Parse(Console.ReadLine());//分割后子文件的长度 byte[] buffer = new byte[subLength]; Console.WriteLine("分割后的文件的路径:"); int subCount = (int)(fileStream.Length + subLength - 1) / subLength;//分割后子文件的数量 for (int i = 0; i < subCount; i++) { int readLength = fileStream.Read(buffer, 0, subLength);//读取的字节数 string subName = fileStream.Name + "." + i + ".txt"; FileStream subFile = File.Create(subName);//创建子文件 subFile.Write(buffer, 0, readLength);//写入子文件 subFile.Close(); Console.WriteLine("文件{0}\t的长度{1}字节",subName,readLength); } fileStream.Close();
这里有个小异常没有解决,望有心人看见给予帮助? 异常消息:system.invalidoperationexception 此流上不支持超时
//创建文本文件 string fileName = Directory.GetCurrentDirectory() + "\\zhiniao.txt"; FileStream file = File.Create(fileName);//创建主文件 int subIndex = 0;//子文件索引 while (File.Exists(file.Name + "." + subIndex + ".txt")) { //打开子文件流 FileStream subFile = new FileStream(file.Name + "." + subIndex + ".txt", FileMode.Open); byte[] buffer = new byte[subFile.Length];//子文件缓存 int readLength = subFile.Read(buffer, 0, buffer.Length);//读取子文件 file.Write(buffer, 0, readLength); subFile.Close(); subIndex++; } file.Close(); StreamReader reader = new StreamReader(fileName); Console.WriteLine(reader.ReadToEnd()); reader.Close();
读取前 读取后
static List<Dictionary<string, string>> GetData(out List<string> columns) { string line; string[] stringArray; char[] charArray = new char[] { ','}; List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); columns = new List<string>(); try { FileStream aFile = new FileStream(@"..\Debug\zhiniao.txt", FileMode.Open); StreamReader sr = new StreamReader(aFile); line = sr.ReadLine(); stringArray = line.Split(charArray); for (int i = 0; i <= stringArray.GetUpperBound(0); i++) { columns.Add(stringArray[i]); } line = sr.ReadLine(); while (line!=null) { stringArray = line.Split(charArray); Dictionary<string, string> dataRow = new Dictionary<string, string>(); for (int j = 0; j <= stringArray.GetUpperBound(0); j++) { dataRow.Add(columns[j], stringArray[j]); } data.Add(dataRow); line = sr.ReadLine(); } sr.Close(); return data; } catch (IOException ex) { Console.WriteLine(ex.ToString()); Console.WriteLine(); return data; }
static void Main(string[] args) { List<string> columns; List<Dictionary<string, string>> myData = GetData(out columns); foreach (string column in columns) { Console.Write("{0,-20}", column); } Console.WriteLine(); foreach (Dictionary<string,string> row in myData) { foreach (string colum in columns) { Console.Write("{0,-20}", row[colum]); } Console.WriteLine(); } }
这里有必要对 FileStream 、StreamReader、StreamWriter类做个初步的解析,这里很重要:
FileStream 提供了已字节的方法读取文件流,经常要结合 StreamReader 、StreamWriter使用(Stream操作的是字符)
有时候我们要随机访问文件中间某点的数据,就必须选择 FileStream 对象执行,本例我已经应用到程序中了(注意本例的 line = sr.ReadLine())
一行一行的读取,指针会随着读取的内容指向读取完内容的末尾 接着读取下一行。
static void Main(string[] args) { try { string fileName = "CompressedFile.txt"; Console.WriteLine("请输入要压缩的字符串,最好是英文!"); string sourceString = Console.ReadLine(); StringBuilder sourceStringMultiplier = new StringBuilder(sourceString.Length * 100);//增长的最大容量 for (int i = 0; i < 100; i++) { sourceStringMultiplier.Append(sourceString); } sourceString = sourceStringMultiplier.ToString(); Console.WriteLine("输入数据的字节数 {0}:", sourceString.Length); SaveCompressedFile(fileName, sourceString); FileInfo compressionFileData = new FileInfo(fileName); Console.WriteLine("压缩后数据的字节数:{0}", compressionFileData.Length); string reconveredString = LoadCompressionFile(fileName);//读取压缩文件并且转换为字符串 reconveredString = reconveredString.Substring(0, reconveredString.Length / 100);// 从此实例检索子字符串。 子字符串从指定的字符位置开始且具有指定的长度。 Console.WriteLine("还原压缩的字符串数据为: {0}", reconveredString); Console.ReadKey(); } catch (Exception) { throw; } } /// <summary> /// 压缩 /// </summary> /// <param name="fileName"></param> /// <param name="data"></param> static void SaveCompressedFile(string fileName, string data) { FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress);//对两个参数的解析,1.要压缩或解压缩的流. 2.用于指示压缩还是解压缩流的枚举值之一. 将文件流压缩 StreamWriter writer = new StreamWriter(compressionStream);//要写入的流 writer.Write(data);//将压缩流写入data writer.Close(); } /// <summary> /// 解压 /// </summary> /// <param name="filename"></param> /// <returns></returns> static string LoadCompressionFile(string filename) { FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read); GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Decompress); StreamReader reader = new StreamReader(compressionStream);//要读取的流 string data = reader.ReadToEnd();//读取文件压缩字节 reader.Close(); return data; }
替换成
C#字符串分割--一个字符串用另一个字符串来分割成字符串字组
static void SplitStringAndSubstitute() { string name = "en_US.txt"; string newname = "en_zhiniao.txt"; string strLine; StringBuilder sreb = new StringBuilder(); try { FileStream aFile = new FileStream(name, FileMode.Open); StreamReader sr = new StreamReader(aFile); strLine = sr.ReadLine(); string[] strArr; string str; while (strLine != null) { strArr = StringSplit(strLine, "] =");//strArr[0].Split('[')[1] 汉字部分 strLine是需要截取额字符串, ] = 是截取字符串的匹配字符串 str =strArr[0]+"] = "+ strArr[0].Split('[')[1] + ";"; sreb.AppendLine(str); strLine = sr.ReadLine(); } aFile.Close(); sr.Close(); using (StreamWriter sw = new StreamWriter(newname)) { sw.Write(sreb); } } catch (Exception) { throw; } }
/// <summary>
/// 将字符串分割成数组
/// </summary>
/// <param name="strSource"></param>
/// <param name="strSplit"></param>
/// <returns></returns> static string[] StringSplit(string strSource, string strSplit) { string[] strtmp = new string[1]; int index = strSource.IndexOf(strSplit, 0); if (index < 0) { strtmp[0] = strSource; return strtmp; } else { strtmp[0] = strSource.Substring(0, index); return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp); } }
/// <summary>
/// 采用递归将字符串分割成数组
/// </summary>
/// <param name="strSource"></param>
/// <param name="strSplit"></param>
/// <param name="attachArray"></param>
/// <returns></returns> static string[] StringSplit(string strSource, string strSplit, string[] attachArray) { string[] strtmp = new string[attachArray.Length + 1]; attachArray.CopyTo(strtmp, 0); int index = strSource.IndexOf(strSplit, 0); if (index < 0) { strtmp[attachArray.Length] = strSource; return strtmp; } else { strtmp[attachArray.Length] = strSource.Substring(0, index); return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp); } }
将简体转换为繁体代码 , 需要添加 .net引用 (Microsoft.VisualBasic):
System.Globalization.CultureInfo cl = new System.Globalization.CultureInfo("zh-CN", false);
string abc = Microsoft.VisualBasic.Strings.StrConv(@"需要将简体转换为繁体的字符放这", Microsoft.VisualBasic.VbStrConv.TraditionalChinese, cl.LCID);
下面这个方法书正则实现替换
static void RegexTest() { using (StreamReader sr = new StreamReader("en_US.txt", Encoding.GetEncoding("utf-8"))) { using (StreamWriter sw = new StreamWriter("02.txt")) { string result; while ((result = sr.ReadLine()) != null) { string str = result; string reg = @".+\[\'([.+\u4E00-\u9FFF.+]+)\'\].+\=\'(.+)\'\;"; Match mat = Regex.Match(str,reg); RegexTest(); if (mat.Success) { string i = mat.Groups[2].Value;//Unfollow string j = mat.Groups[1].Value;//取消关注 string m = mat.Groups[0].Value;//"$language['取消关注'] ='Unfollow';" string newLine = str.Replace(mat.Groups[2].Value, mat.Groups[1].Value); sw.WriteLine(newLine); } } } } Console.WriteLine("成功写入!"); Console.ReadKey(); }
先引用命名空间:using System.Text;和using System.IO; FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open, FileAccess.Read, FileShare.None); StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936)); string str = ""; string s = Console.ReadLine(); while (str != null) { str = sr.ReadLine(); string[] xu = new String[2]; xu = str.Split(','); string ser = xu[0]; string dse = xu[1]; if (ser == s) { Console.WriteLine(dse);break; } } sr.Close();
另外也可以将数据库数据导入到一个txt文件,实例如下:
//txt文件名 string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt"; OleDbConnection con = new OleDbConnection(conStr); con.Open(); string sql = "select ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from TSD_PO014"; //OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon); //OleDbDataReader myreader = mycom.ExecuteReader(); //也可以用Reader读取数据 DataSet ds = new DataSet(); OleDbDataAdapter oda = new OleDbDataAdapter(sql, con); oda.Fill(ds, "PO014"); DataTable dt = ds.Tables[0]; FileStream fs = new FileStream(Server.MapPath("download/" + fn), FileMode.Create, FileAccess.ReadWrite); StreamWriter strmWriter = new StreamWriter(fs); //存入到文本文件中 //把标题写入.txt文件中 //for (int i = 0; i <dt.Columns.Count;i++) //{ // strmWriter.Write(dt.Columns[i].ColumnName + " "); //} foreach (DataRow dr in dt.Rows) { string str0, str1, str2, str3; string str = "|"; //数据用"|"分隔开 str0 = dr[0].ToString(); str1 = dr[1].ToString(); str2 = dr[2].ToString(); str3 = dr[3].ToString(); str4 = dr[4].ToString().Trim(); strmWriter.Write(str0); strmWriter.Write(str); strmWriter.Write(str1); strmWriter.Write(str); strmWriter.Write(str2); strmWriter.Write(str); strmWriter.Write(str3); strmWriter.WriteLine(); //换行 } strmWriter.Flush(); strmWriter.Close(); if (con.State == ConnectionState.Open) { con.Close(); }
代码收集源于书本 :C#程序设计经典300例 、C# 入门经典(第五版),一些自我的理解、学习中写的程序
今天就统计到这里,会持续跟进!