0

我将这个简单的代码用于日志文件。

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

3 回答 3

1

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

于 2013-04-21T18:20:40.337 回答
1

如果你想要windows zipping。然后检查一下: 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);
    }
 }
}
于 2017-05-04T13:08:12.820 回答
-1
  // for moving
 File.Move(SourceFile, DestinationFile); // store in dateTime directory  to move file.

//压缩文件的方法

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();
           }
于 2015-06-02T21:17:17.190 回答