首页 > 代码库 > 读写文件

读写文件

 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     }

 

读写文件