2012-06-04 26 views
-1

我在单个文件夹中有多个文本具有不同名称的文件。我想一个接一个地读取所有文件 - >> *仅在第一个完成后读取第二个文件。阅读成功后它应该从目录中删除文件。我可以读取单个文件。但是当我试图读取所有文件在一个镜头它给错误。 如何使用线程读取和删除文件。 所有文件格式相同。多个文件读取问题

我的示例代码:

 StreamReader objReader = new StreamReader("c:\codeo\testm.txt"); 
     string sLine=""; 
     ArrayList arrText = new ArrayList(); 

     while (sLine != null) 
     { 
      sLine = objReader.ReadLine(); 
      if (sLine != null) 
       arrText.Add(sLine); 
     } 
        objReader.Close(); 

     foreach (string sOutput in arrText) 
      Console.WriteLine(sOutput); 
     Console.ReadLine(); 

对德尔:

   private void btnDelete_Click(object sender, EventArgs e) 
      { 
       if (File.Exists(fileLoc)) 
       { 
       File.Delete(fileLoc); 
       } 
      } 
+5

它是一个很好的习惯接受人们的答案,然后再问你新的问题。 – YavgenyP

+0

你在ASP.NET应用程序中使用这段代码吗?请修复标签,这当然不是asp-classic –

回答

0

试试这个代码

DirectoryInfo di = new DirectoryInfo("c:\\codeo\\"); 
FileInfo[] fiArray = di.GetFiles(); 

foreach (FileInfo fi in fiArray) 
{ 
    StreamReader objReader = new StreamReader(fi.FullName); 
    string sLine = ""; 
    ArrayList arrText = new ArrayList(); 

    while (sLine != null) 
    { 
     sLine = objReader.ReadLine(); 
     if (sLine != null) 
      arrText.Add(sLine); 
    } 
    objReader.Close(); 

    foreach (string sOutput in arrText) 
     Console.WriteLine(sOutput); 
    Console.ReadLine(); 

} 
0

这需要一些更多的澄清,比如你收到了什么错误。我会这样做的方式是:

//Store all filenames within a List<string> 
public void ReadFiles(List<string> filenames) 
{ 
    string line = null; 
    foreach(string file in filenames) 
    { 
     //The using will manage the closing and handle exceptions safely 
     using(StreamReader reader = new StreamReader(file)) 
     { 
      while((line = reader.readLine()) != null) 
      Console.WriteLine(line); 
     } 
     if(File.Exists(file)) 
      File.Delete(file); 
    } 
} 

此代码未经测试,但我相信它应该正常工作。这对你有帮助吗?我根据您阅读后需要删除的文件编写了这个文件 - 基于按钮的删除应该很容易实现。如果你需要更多的澄清或帮助发表评论。