我需要将文件夹从文件夹X压缩到文件夹Y.当文件夹X中的文件压缩到文件夹Y中时,需要删除文件夹X中的文件。 zip名称必须是该文件夹中包含.DBS的文件的名称。
所以我需要阅读.DBS文件的文件名是什么。然后我需要将文件夹X中的所有文件压缩到文件夹Y,名称为:"文件名" (这与.DBS文件相同)如果文件是压缩文件并且在文件夹Y中,则需要从文件夹X中删除它们。
我目前获得的代码将文件夹X的文件也移动Y.所以这是一个开始。我的问题是如何获取文件的名称也是zip文件夹名称。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
namespace Ramasoftzipper
{
class Program
{
static void Main(string[] args)
{
string fileName = @"160001.DBS";
string sourcePath = @"C:\RMExport";
string targetPath = @"C:\Exportrm";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
string startPath = @"C:\RMExport";
string zipPath = (fileName);
string extractPath = @"C:\Exportrm";
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
}
}
}
提前致谢。
答案 0 :(得分:2)
(只解释这个因为我认识你,你需要学习这些东西,哟:P)
你可以试试这样的东西,在代码中阅读评论以获取更多信息,此代码仅向您展示如何压缩文件夹中的所有文件,尝试自己添加某些扩展的下一步
//files to zip, you can also use the same method as above to let the user determine what path to zip
string path = @"C:\Users\WsLocal.NL-ROE2-W297\Pictures";
string zipPath = @"C:\Users\WsLocal.NL-ROE2-W297\Desktop\zip\result.zip";
//zip files
ZipFile.CreateFromDirectory(path, zipPath);
string[] files = Directory.GetFiles(path);
//some debugging
foreach (string filePath in files)
{
Console.WriteLine(filePath);
}
//wait untill user presses enter
Console.ReadLine();
<强> [编辑] 强>
将zip文件的名称设置为文件名:
替换
string zipPath = @"C:\Users\WsLocal.NL-ROE2-W297\Desktop\zip\result.zip";
与
//get all files from directory decladed by path
string[] files = Directory.GetFiles(path);
//select the 1st one and delete the folder information so just the file name is left with it's extention
string zipName = files[0].Replace(path, "");
//delete the extention
int index = zipName.IndexOf(".");
if (index > 0)
zipName = zipName.Substring(0, index);
//assemble the zip location with the generated file name
string zipPath = @"C:\Users\WsLocal.NL-ROE2-W297\Desktop\zip\"+ zipName + ".zip";
并删除
string[] files = Directory.GetFiles(path);
下
//zip files
ZipFile.CreateFromDirectory(path, zipPath);