2014-01-30 202 views
1

我只是要合并在一个给定的目录中的所有文本文件,类似于下面的命令提示符下命令:合并多个文本文件 - StreamWriter不写入一个文件?

cd $directory 
copy * result.txt 

我已经写了下面的代码,它几乎完成我想要的东西,但它做一些奇怪的事情。当StreamWriter写入第一个文件(或i = 0)时,它实际上并不写入任何内容 - 文件大小仍为0字节,尽管第一个文件大约为300 KB。但是,其他文件写入成功执行。

如果我将命令提示符的输出与来自C#代码的输出比较,可以看到缺少大块文本。此外,命令提示符结果为1,044 KB,其中C#结果为700 KB。

string[] txtFiles = Directory.GetFiles(filepath); 
using (StreamWriter writer = new StreamWriter(filepath + "result.txt")) 
{ 
    for (int i = 0; i < txtFiles.Length; i++) 
    { 
     using (StreamReader reader = File.OpenText(txtFiles[i])) 
     { 
      writer.Write(reader.ReadToEnd()); 
     } 
    } 
} 

我使用的StreamWriter/StreamReader不正确?

回答

1

在这里,希望它可以帮助你。注意:通过从一个流复制到另一个,您可以节省一些内存并大大提高性能。

class Program 
{ 
    static void Main(string[] args) 
    { 
     string filePath = @"C:\Users\FunkyName\Desktop"; 
     string[] txtFiles = Directory.GetFiles(filePath, "*.txt"); 

     using (Stream stream = File.Open(Path.Combine(filePath, "result.txt"), FileMode.OpenOrCreate)) 
     { 
      for (int i = 0; i < txtFiles.Length; i++) 
      { 
       string fileName = txtFiles[i]; 
       try 
       { 
        using (Stream fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)) 
        { 
         fileStream.CopyTo(stream); 
        } 
       } 
       catch (IOException e) 
       { 
        // Handle file open exception 
       } 
      } 
     } 
    } 
} 
+0

当程序再次运行在同一个目录中时,FileMode.OpenOrCreate'会再次将所有文件添加到输出文件。而是使用'FileMode.Create'来完全覆盖它或'FileMode.CreateNew'来获取它已经存在的异常。 – Herdo

+0

@Herdo该程序在运行之前删除与'filePath'变量匹配​​的所有现有文件夹,因此该实现应该是可以的。谢谢! – TimeBomb006

1

简约执行,读取字节,写他们,而不是使用流阅读 - 请注意,你应该正确处理IOException异常,以避免不当行为:

var newline = Encoding.ASCII.GetBytes(Environment.NewLine); 
var files = Directory.GetFiles(filepath); 
try 
{ 
    using (var writer = File.Open(Path.Combine(filepath, "result.txt"), FileMode.Create)) 
     foreach (var text in files.Select(File.ReadAllBytes)) 
     { 
      writer.Write(text, 0, text.Length); 
      writer.Write(newline, 0, newline.Length); 
     } 
} 
catch (IOException) 
{ 
    // File might be used by different process or you have insufficient permissions 
} 
0

我写你的代码,它正常工作!只有改变行:

using (StreamWriter writer = new StreamWriter(filepath + "result.txt")) 

到:

using (StreamWriter writer = new StreamWriter(filepath + "/result.txt")) 

我猜你看不到的文件,因为它被保存在另一个文件夹。

相关问题