创建一个文件,然后创建一个zip并将其移动到另一个目录

问题描述:

我使用这个简单的代码作为日志文件。创建一个文件,然后创建一个zip并将其移动到另一个目录

private string LogFile 
    { 
     get 
     { 
      if (String.IsNullOrEmpty(this.LogFile1)) 
      { 
       string fn = "\\log.txt"; 
       int count = 0; 
       while (File.Exists(fn)) 
       { 
        fn = fn + "(" + count++ + ").txt"; 
       } 
       this.LogFile1 = fn; 
      } 
      return this.LogFile1; 
     } 
    } 

我怎么能每个日志文件移动到另一个目录(文件夹),并使其像存档.ZIP? 这将运行一次,我会每天有一个文件。

文件移动:

public static void Move() 
    { 
     string path = ""; 
     string path2 = ""; 
     try 
     { 
      if (!File.Exists(path)) 
      { 
       using (FileStream fs = File.Create(path)) { } 
      } 
      if (File.Exists(path2)) 
       File.Delete(path2); 

      File.Move(path, path2); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("The process failed: {0}", e.ToString()); 
     } 
    } 
+0

'System.IO.File.Move'和压缩文件:http://*.com/questions/940582/how-do-i-zip-a -file-在-C-使用-NO-第三方的API – 2013-04-21 18:21:23

+0

上面的代码将产生用于环路如的每个迭代一个奇怪的文件名: - “\\ log.txt的(0)的.txt”,“\ \ log.txt(0).txtlog.txt(1).txt“等等。您可能需要重新检查文件名称生成逻辑 – 2013-04-21 18:26:36

+0

@PrahaladDeshpande是的,我知道有线名称。我现在重新检查一下。这是因为我将所有日志存储在一个文件夹中。而现在,当我将它们移到我可以用正常的名称可以.. – 2013-04-21 18:31:54

对于移动文件,你可以使用File类的静态方法Move。对于zip文件,您可以查看GZipStreamZipArchive类。

+0

提问者希望拉上和不问的gzip – 2013-04-21 18:39:36

+1

'GZipStream'压缩使用GZIP单个流。问题是关于ZIP。所以'ZipArchive'就是需要的。 – 2013-04-21 19:57:22

+0

谢谢@David。我用你的消化来编辑我的答案。 – 2013-04-21 20:05:20

// for moving 
File.Move(SourceFile, DestinationFile); // store in dateTime directory to move file. 

//为zip文件

private static void CompressFile(string path) 
      { 
       FileStream sourceFile = File.OpenRead(path); 
       FileStream destinationFile = File.Create(path + ".gz"); 

       byte[] buffer = new byte[sourceFile.Length]; 
       sourceFile.Read(buffer, 0, buffer.Length); 

       using (GZipStream output = new GZipStream(destinationFile, 
        CompressionMode.Compress)) 
       { 
        Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name, 
         destinationFile.Name, false); 

        output.Write(buffer, 0, buffer.Length); 
       } 

       // Close the files. 
       sourceFile.Close(); 
       destinationFile.Close(); 
      } 

方法如果你想让Windows荏苒。 然后检查了这一点: https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx

using System; 
using System.IO; 
using System.IO.Compression; 

namespace ConsoleApplication 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     string startPath = @"c:\example\start"; 
     string zipPath = @"c:\example\result.zip"; 
     string extractPath = @"c:\example\extract"; 

     ZipFile.CreateFromDirectory(startPath, zipPath); 

     ZipFile.ExtractToDirectory(zipPath, extractPath); 
    } 
} 
}