首页 > 代码库 > 读写文件
读写文件
1 /// <summary> 2 /// 写字符串到特定文件中 3 /// </summary> 4 /// <param name="content"></param> 5 /// <param name="filePath"></param> 6 private static void WriteContentToFile(string content,string filePath) 7 { 8 List<int> byteLengths = new List<int>(); 9 FileStream fileStream = null;10 BufferedStream writer = null;11 try12 {13 fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);14 writer = new BufferedStream(fileStream);15 //sum read byte length16 byte[] contentBytes = System.Text.Encoding.Default.GetBytes(content);17 18 writer.Write(contentBytes, 0, contentBytes.Length);19 20 }21 catch (Exception ex)22 {23 throw ex;24 }25 finally26 {27 writer.Close();28 fileStream.Close();29 }30 }
1 /// <summary> 2 /// 从文件中读取包含特定文本的区域内容 3 /// 如下一共有三段文本,需要读取每段文本的区域内容 4 /// ##1## 5 ///^XA 6 ///... 7 ///^XZ 8 ///##2## 9 ///^XA10 ///...11 ///^XZ12 ///##3##13 ///^XA14 ///...15 ///^XZ16 /// </summary>17 /// <param name="prnFilePath"></param>18 private string[] ReadContent(string prnFilePath) 19 {20 //区域内容的数量,如上例示例中的321 int zoneQty = 3;22 string[] contents = new string[zoneQty];23 24 FileStream fileStream = null;25 StreamReader streamReader = null;26 try27 {28 fileStream = new FileStream(prnFilePath, FileMode.Open, FileAccess.Read);29 streamReader = new StreamReader(fileStream, System.Text.Encoding.ASCII);30 31 for (int zoneIndex = 0; zoneIndex < zoneQty; zoneIndex++)32 {33 StringBuilder contentStringBuilder = new StringBuilder();34 string readLine = streamReader.ReadLine();35 while (readLine != null)36 {37 contentStringBuilder.Append(readLine);38 contentStringBuilder.Append("\r\n");39 //^XZ是特定内容。即代表一段区域内容的结束40 if (readLine.Contains("^XZ"))41 {42 //如果读取到结束标记,则读取下一个区域的文本43 contents[zoneIndex] = contentStringBuilder.ToString();44 break;45 }46 else47 {48 //如没有读取到结束标记,则继续读取下一行内容49 readLine = streamReader.ReadLine();50 }51 }52 }53 }54 catch (Exception ex)55 {56 throw ex;57 }58 finally59 {60 streamReader.Close();61 fileStream.Close();62 }63 64 return contents;65 }
读写文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。