【问题标题】:How to add a txt file in archive using System.IO ZipFile如何使用 System.IO ZipFile 在存档中添加 txt 文件
【发布时间】:2018-02-06 09:20:04
【问题描述】:

我尝试使用 System.IO 在 .rar 存档中添加一个 txt 文件,但每次存档都是空的 - 0kb。

我收到如下错误消息:

Unhandled Exception: System.IO.IOException: The process cannot access the file 'C:\M\Telegrami\Yambol.zip' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.Compression.ZipFileExtensions.DoCreateEntryFromFile(ZipArchive destination, String sourceFileName, String entryName, Nullable`1 compressionLevel)
   at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable`1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding)
   at System.IO.Compression.ZipFile.CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, CompressionLevel compressionLevel, Boolean includeBaseDirectory)
   at SEND_Plovdiv.WebRequestGetExample.Main() in C:\Users\admin\Desktop\ALL PROJECTS\SEND Plovdiv\SEND Plovdiv\SEND Plovdiv\Program.cs:line 36

有时当我第二次启动项目时,txt文件被添加到archive.rar,但错误信息仍然存在。

我想将此txt文件添加到.rar并通过ftp发送..

我的代码在这里:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;

using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SEND_Plovdiv
{


public class WebRequestGetExample
{

    public static void Main()
    {
        string[] lineOfContents = File.ReadAllLines(@"C:\\M\send.txt");

        string username = "";
        string password = "";
        foreach (var line in lineOfContents)
        {
            string[] tokens = line.Split(',');
            string user = tokens[0];
            string pass = tokens[1];

            username = user;
            password = pass;
        }

        string pathFile = @"C:\M\Telegrami\";
        string zipPath = @"C:\M\Telegrami\Yambol.zip";

        ZipFile.CreateFromDirectory(pathFile, zipPath, CompressionLevel.Fastest, true);

        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://IP to FTP/Yambol.txt");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.  
            request.Credentials = new NetworkCredential(username, password);

            // Copy the contents of the file to the request stream.  
            StreamReader sourceStream = new StreamReader(@"C:\M\Telegrami\Yambol.txt");
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

            response.Close();

    }
}

}

所以存档已创建,但我只想提取文件,因为当我提取时,我只想提取文件而不是文件夹。现在我有新错误,但存档已创建。如果可能的话,我只想获取一个没有文件夹的 .txt 文件?以及如何消除错误:)

【问题讨论】:

  • 我怀疑它有很大的不同,但是 "C:\\" ?如果你 @'d 为什么要用双斜线?
  • 如果我使用单斜杠错误是一样的... :(
  • ZipFile.CreateFromDirectory() 将目录名称作为其第一个参数,但您传递给它的是文件名。您是要创建整个目录的存档还是只创建一个文件?
  • .rar - 这里的选择不好。需要rar吗?另见:stackoverflow.com/questions/31382210/…
  • 也许它不高兴是因为你给它一个文件而不是一个目录?

标签: c# .net console-application ziparchive system.io.file


【解决方案1】:

正如 cmets 中提到的,问题ZipFile.CreateFromDirectory() 将目录名称作为它的第一个参数,但您传递的是文件名。这里是documentation

sourceDirectoryName --- 要归档的目录的路径,指定为相对路径或 绝对路径。相对路径被解释为相对于 当前工作目录。


这里是解决方案

string pathFile = @"C:\M\Telegrami\";
string zipPath = @"C:\M\Yambol.zip";

ZipFile.CreateFromDirectory(pathFile, zipPath, CompressionLevel.Fastest, true);

如果您需要仅文件,而不是整个目录重写代码,则将方法CreateFromDirectory()的最后一个参数从true更改为false强>:

ZipFile.CreateFromDirectory(pathFile, zipPath, CompressionLevel.Fastest, false);

查看documentation:

includeBaseDirectory --- true 包含来自 sourceDirectoryName 的目录名称 档案的根目录; false 仅包含 目录。


您收到错误

进程无法访问文件“C:\M\Telegrami\Yambol.zip”,因为 它正被另一个进程使用。

因为它会尝试将 Yambol.zip 放入当前进程正在使用的文件夹中,因为您同时压缩该文件夹。要使其正常工作,您必须将其放入另一个文件夹中,尝试如上所示定义文件夹。


LocEngineer 的宝贵意见是使用 .zip 扩展名,而不是 .rar


【讨论】:

  • 请不要对 zip 文件使用 rar 扩展名!
  • @Валерия Благовест,我更新了我的答案。希望对你有帮助。
  • 谢谢各位,问题解决了!
  • @Валерия Благовест,不客气。如果对您有帮助,您可以接受和/或投票支持答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 2012-10-22
  • 2012-01-05
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多