Ch25 文件和注册表操作(2)-- 读写文件

老早之前就有一个想法,写一个小程序,可以读取文档,可以查找替换关键字,其实也是很简单的,正好最近看到文件系统这章,今天下午没事也就做了一个,这里总结一下:

1.用StreamReader读取文本文件,编码用Encoding.Default。

 StreamReader sr = new StreamReader(filePath,Encoding.Default);
 rtbContent.Text = sr.ReadToEnd();
 sr.Close();   //释放锁定资源

2.统计要查找的字符,使用了String.indexof(),for循环条件。

string content = rtbContent.Text.Trim();
string key = txtInput.Text.Trim();
int count = 0;
int start;
                    
for (start = 0; (start = content.IndexOf(key, start)) > -1; start = start + key.Length)
{ count
++; } MessageBox.Show("" + key + "” 共出现了 " + count.ToString() + "");

此小程序的网盘地址:http://pan.baidu.com/s/1hqAAZpM

--------------------------------总结完毕-------------------------------------------------------------------------------------------

1.File类的ReadAll、WriteAll方法(.net framework 2.0)

2.流的概念:

  流是一个用于传送数据的对象。数据的传送有两个方向:

  如果数据从外部源传输到程序中,这就是读取流;如果暑假从程序传输到外部源,这就是写入流。

3.FileStream类:用于读写二进制文件。构造FileStream实例,需要以下4条信息:(.net framework 1.x,在2.0推出前总使用它)

  要访问的文件

  表示如何打开文件的模式-FileMode

  表示访问文件的方式-FileAccess

  共享访问-FileShare

4.读写文本文件的StreamReader类和StreamWriter类

  可以把StreamReader关联到FileStream上:

  FileStream fs=new FileStream("C: eadme.txt",FileMode.Open,FileAccess.Read,FileShare.None);

  StreamReader sr=new StreamReader(fs);

  FileInfo实例中获得StreamReader

  FileInfo myFile=new FileInfo("C: eadme.txt");

  StreamReader sr=myFile.OpenText();

原文地址:https://www.cnblogs.com/wyh19930325/p/3881247.html