我要遍历某目录下的所有文件及其子文件夹下的所有文件(),然后把其内容存放到一个txt文件中.
现在报错说,txt文件正在由另一个进程访问.哪位仁兄帮忙解决一下代码如下:
private void readfile(string dir,string doc,string extType)
{
string[] names=System.IO.Directory.GetFiles(dir,"*."+extType);
//遍历文件
if(names.Length !=0)
{
         string csFile;
string title="//============";
string titleEnd="===========";
System.IO.FileStream  fs;
System.IO.StreamReader reader;
System.IO.StreamWriter writer;
string content="";
for(int i=0;i<names.Length;i++)
{
//apsx file
try
{
fs=new System.IO.FileStream(names[i].ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
reader=new System.IO.StreamReader(fs);
content=reader.ReadToEnd();
reader.Close();
fs.Close(); writer=new System.IO.StreamWriter(doc,true);
writer.WriteLine(title + names[i].ToString() + titleEnd);
writer.WriteLine(content);
writer.Flush();
writer.Close();
//fs.Close();         //aspx.cs file
csFile=names[i].ToString()+".cs";
fs=new System.IO.FileStream(csFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
reader=new System.IO.StreamReader(fs);
content=reader.ReadToEnd();
reader.Close();
fs.Close();

writer=new System.IO.StreamWriter(doc,true);
         writer.WriteLine(title + csFile + titleEnd);
writer.WriteLine(content);
writer.Flush();
writer.Close();
        }
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//遍历目录
string[] subDirectorys=System.IO.Directory.GetDirectories(dir);
if(subDirectorys.Length !=0)
{
for(int i=0; i<subDirectorys.Length; i++)
{
readfile(subDirectorys[i].ToString(),doc,extType);
}
}
}