2013-04-21 122 views
0

我使用這個簡單的代碼作爲日誌文件。創建一個文件,然後創建一個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://stackoverflow.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

回答

1

對於移動文件,你可以使用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

-1
// 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(); 
      } 
1

方法如果你想讓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); 
    } 
} 
} 
相關問題