-1

I try to add a txt file in .rar archive using System.IO, but every time the archive is empty - 0kb.

I receive error message like this:

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

Sometime when I start the project for second time the txt file is added to archive.rar but the error message is still there.

I want to add this txt file to .rar and send by ftp..

My code is here:

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

    }
}

}

So the archive is create but I want to take only the file, because when I extract I want to extract only the file not the folder.. For now I have new error but the archive is created. I want only to take a .txt file without the folder if its possible ? And how to remove the error :)

1 Answers1

1

As was mentioned in comments, the problem is that ZipFile.CreateFromDirectory() takes a directory name as it's first parameter, but you are passing a filename. Here is documentation:

sourceDirectoryName --- The path to the directory to be archived, specified as a relative or absolute path. A relative path is interpreted as relative to the current working directory.


Here is the solution:

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

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

If you need only file, not whole directory rewrite code next way, change the last parameter of the method CreateFromDirectory() from true to false:

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

Check it in documentation:

includeBaseDirectory --- true to include the directory name from sourceDirectoryName at the root of the archive; false to include only the contents of the directory.


Your're getting error:

The process cannot access the file 'C:\M\Telegrami\Yambol.zip' because it is being used by another process.

as it would try to put Yambol.zip into folder which is in use of the current process, because you are zipping that folder same time. To make it work you would have to put it into another folder, try to define folders as shown above.


Valuable remark from LocEngineer is to use .zip extension, instead of .rar.


Alex
  • 790
  • 7
  • 20