C#实现文本文件字符过滤

本人初学C#,最近才接触数组、流,编写了一个小程序。几乎没实用价值,只用来记录自己所学。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 namespace namespace1   //命名空间
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             FileStream file = File.Open("F:/filename.txt"/*初始文件路径*/, FileMode.Open, FileAccess.Read);//打开初始文件
13             FileStream file2 = File.Open("F:/filename2.txt"/*过滤后文件*/, FileMode.Create, FileAccess.Write);//创建处理后的文件
14             file2.Close();//关闭file2文件流
15             byte[] array = new byte[file.Length];//初始化字节数组
16             file.Read(array, 0, array.Length);//读取流中的数据并把它写入字节数组中
17             file.Close();   //关闭file1文件流  
18             string str = Encoding.Default.GetString(array);  //将字节数组转化为字符串
19             char[] ch = str.ToCharArray();  //将字符串转化为字符数组
20             string str1 = "";           
21             foreach (char c in ch)  //遍历ch 
22             {
23                 if ((c != '1') & (c != '2') & (c != '3') & (c != '4') & (c != '5') & (c != '6') & (c != '7') & (c != '8') & (c != '9') & (c != '0'))
24                 //判断字符不等于数字,可根据实际情况更改过滤条件   
25                 {
26                     str1 = str1 + c.ToString();//字符串拼接
27                 }
28             }
29             string fullPath = "F:/filename2.txt";                                  //将字符串写入文件
30             if (System.IO.File.Exists(fullPath)) 
31             {
32                 using (StreamWriter sw = new StreamWriter(fullPath, false, Encoding.Default)) 
33                 {
34                    sw.WriteLine(str1); 
35                 } 
36             }
37         }
38     }
39 }
View Code

 

转载于:https://www.cnblogs.com/pwenlee/p/4112310.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值