I didn't find "ZipFile" class in the "System.IO.Compression" namespace - c#

I can't use "Zipfile" class in the name space "System.IO.Compression" my code is :
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, CompressionLevel.Fastest,true);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
the error is :
The name 'zipfile' does not exist in the current context
How I can solve it ?

You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile
<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).
For info, you can find the assembly and .NET version(s) from MSDN

For those who are green programmers in .NET, to add the DLL reference as MarcGravell noted, you follow these steps:
To add a reference in Visual C#
In Solution Explorer, right-click the project node and click Add Reference.
In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
Select the components you want to reference, and then click OK.
From the MSDN Article, How to: Add or Remove References By Using the Add Reference Dialog Box.

you can use an external package if you cant upgrade to 4.5. One such is Ionic.Zip.dll from DotNetZipLib.
using Ionic.Zip;
you can download it here, its free. http://dotnetzip.codeplex.com/

Just go to References and add "System.IO.Compression.FileSystem".

In solution explorer, right-click References, then click to expand assemblies, find System.IO.Compression.FileSystem and make sure it's checked. Then you can use it in your class - using System.IO.Compression;
Add Reference Assembly Screenshot

A solution that helped me:
Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse >
Search for System.IO.Compression.ZipFile and install it

System.IO.Compression is now available as a nuget package maintained by Microsoft.
To use ZipFile you need to download System.IO.Compression.ZipFile nuget package.

I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.
To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.
And for reference on how to use this and iterate through for a certain file extension as example you could do this:
#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
|| Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
//NOTE: I recommend you add path checking first here, added the below as example ONLY.
string ZIPfileLocationHere = #"C:\Users\Name\Desktop\test.zip";
string EXTRACTIONLocationHere = #"C:\Users\Name\Desktop";
//Opens existing zip file.
ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);
//Read all directory contents.
List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
foreach (ZipStorer.ZipFileEntry entry in dir)
{
try
{
//If the files in the zip are "*.png or *.PNG" extract them.
string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
if (HasPNGExtension(path))
{
//Extract the file.
zip.ExtractFile(entry, path);
}
}
catch (InvalidDataException)
{
MessageBox.Show("Error: The ZIP file is invalid or corrupted");
continue;
}
catch
{
MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
continue;
}
}
zip.Close();
}

Add System.IO.Compression.ZipFile as nuget reference it is working

The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll
And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).
I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7
https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530

Related

System.IO.Compression does not accept a bool in "ExtractToDirectory"

I am kinda new to C# and visual studio.
I try to unzip a zip and overwrite files if they already exist with the following function:
using System.IO;
using System.IO.Compression;
ZipFile.ExtractToDirectory(gameZip, rootPath, true);
But it wont accept a bool argument as it should be if i can trust this document:
(https://github.com/dotnet/runtime/blob/main/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.Extract.cs#L188)
Looking into the package i am using it seems like it is not supported this way, but i use the same package:
public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
{
ExtractToDirectory(sourceArchiveFileName, destinationDirectoryName, null);
}
public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, Encoding entryNameEncoding)
{
if (sourceArchiveFileName == null)
{
throw new ArgumentNullException("sourceArchiveFileName");
}
using ZipArchive source = Open(sourceArchiveFileName, ZipArchiveMode.Read, entryNameEncoding);
source.ExtractToDirectory(destinationDirectoryName);
}
So my question is,
Why do i have a different version even tho i installed packages from microsoft over the NuGet Package installer:
System.IO.Compression.ZipFile and System.IO.Compression (4.3.0)
(.NET Framework 4.8)
I tried to find my way through this labyrinth of packages but after 2 days of being stuck at such a simple task just made me post my first question here in Stackoverflow.
I hope someone can help me. :D
I tried to extract a zip and set the overwrite boolean to "true" so it overwrite existing files.

Unity throws an error “CS0246: The type or namespace name ‘SharpKml’ could not be found

I am researching how to generate environments in Unity using GIS data in KML format. I came across the SharpKML plugin and it seems to be ideal for my needs.
However, I am experiencing a strange error in that Unity throws an error
“CS0246: The type or namespace name ‘SharpKml’ could not be found (are you missing a using directive or an assembly reference?)”
The reference is added to VS and I have using SharpKML.Dom and using SharpKML.Engine entries which compile in VS with no problems.
But Unity still throws the error.
I have installed via NuGet and have also downloaded the SharpKML source code and rebuilt the dll on my machine and referenced directly with no change. VS also seems to drop the reference intermittently.
Have you come across this problem before or have any idea what is causing it?
The version of Unity is 2019.1.4f1 and the the version of VS is 2017 running framework 4.7.03062
I have recreated the project on a different machine on a different network and experience the same problem.
using UnityEngine;
using System.IO;
using System.Linq;
using SharpKml.Dom;
using SharpKml.Engine;
public class RenderKML : MonoBehaviour
{
public string KLMPath;
// Start is called before the first frame update
void Start()
{
string kmlPth = "Assets\\kml";
GetKMLFiles(kmlPth);
}
private void GetKMLFiles(string pth)
{
if (pth != null)
{
DirectoryInfo dir = new DirectoryInfo(pth);
FileInfo[] info = dir.GetFiles("*.kml");
foreach (FileInfo f in info)
{
print(f.FullName);
GetKMLData(f);
}
}
}
private void GetKMLData(FileInfo fI)
{
// This will read a Kml file into memory.
Stream fs = new FileStream(fI.FullName, FileMode.Open);
KmlFile file = KmlFile.Load(fs);
Kml kml = file.Root as Kml;
if (kml != null)
{
foreach (var placemark in kml.Flatten().OfType<Placemark>())
{
print(placemark.Name);
}
}
}
}
Every time you press "Run", unity rewrites project files. You cant simply use nuget or add references from external projects. You should download all SharpKML dll files and put them in Assets folder manually. See this for more information: https://answers.unity.com/questions/458300/how-to-use-a-external-dll.html
You need to use the Plugin folder in Unity3D. Download your Package or DLL and put it there.
This link can be helpful

Assemblies refer to the same metadata but only one is a linked reference; consider removing one of the references

I am currently dealing with the error word for word:
Assemblies 'C:\Users\Jake\Desktop\AudioFileSorter\AudioFileSorter\obj\Debug\Interop.QTOControlLib.dll' and 'C:\Users\Jake\Desktop\AudioFileSorter\AudioFileSorter\libs\Interop.QTOControlLib.dll' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references.
My references include several files:
AxInterop.QTOControlLib.dll
Interop.QTOControlLib.dll
Interop.QTOLibrary.dll
Interop.Shell32.dll
taglib-sharp.dll
These files are all located and referenced from a folder called libs within the base location for my project: AudioFileSorter\AudioFileSorter\libs\
An additional control reference was included as the Apple QuickTime Control 2.0 from the COM references. With the exception of this reference all other references were added by right clicking 'References' in the Solution Explorer and clicking 'Add Reference' and then browsing the libs folder to pull dll file.
Obviously, I have no idea what I am doing and I don't know how to solve it. The project worked fine yesterday and after trying to build the project to a release build everything got messed up and now I have this error. I have tried removing one of the duplicate references but then i end up just missing the reference when the app calls it during this code line:
private void SortM4PFiles(string[] files)
{
WriteLine("Begin compiling .m4p files...");
foreach (string file in files)
{
axQTControl1.URL = file;
// Create new movie object
QTOLibrary.QTMovie mov = new QTOLibrary.QTMovie();
mov = axQTControl1.Movie;
string title = mov.Annotation[(int)QTAnnotationsEnum.qtAnnotationFullName];
string artist = mov.Annotation[(int)QTAnnotationsEnum.qtAnnotationArtist];
string album = mov.Annotation[(int)QTAnnotationsEnum.qtAnnotationAlbum];
songs.Add(new Song(title, album, artist, file));
songs[songs.Count - 1].setType(".m4p");
WriteLine("Evaluated " + title);
}
// Make sure the previous .m4p is not in use
// This will prevent an IOException when the file is in use and cannot be moved
axQTControl1.URL = "";
}
Any help or explanation would be greatly appreciated. Thank you.
This was the tutorial for using the QuickTime control and reading m4p and m4a metadata.
I was trying to convert one project from packages.config to PackageReference... & I got this issue. After looking into it, I realized that, there are two references added for the same dll.
How? One from nuget & one from local COM dll. I had remove one reference to fix the issue.

System.Printing not found( C# )?

I am trying to run the following example from MSDN:
using System.Printing;
public class PrintTest {
public static void Main(string[] args)
{
// Create the printer server and print queue objects
LocalPrintServer localPrintServer = new LocalPrintServer();
PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
// Call AddJob
PrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob();
// Write a Byte buffer to the JobStream and close the stream
Stream myStream = myPrintJob.JobStream;
Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.");
myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
myStream.Close();
}
}
but the compiler is complaining
The type or namespace Printing does not exist in the namespace
System(are you missing an assembly reference) ?
How do I solve this issue ?
EDIT: How do I add a reference for command line compiled application ( Not Visual Studio)
From the command line something like csc /reference:lib\System.Printing.dll
Original Answer
Project > Add Reference, then under 'Assemblies > Framework'.
Choose System.Printing.
You can find out which Assembly you need to add a reference to by Googling the namespace followed by the word 'assembly'. In your case:
System.Printing assembly
The second result is from MSDN and indicates which assembly System.Printing can be found in.
From Command prompt
Create a public reference
/reference:[alias=]filename
/reference:filename
Where
Arguments
filename
The name of a file that contains an assembly manifest. To import more than one file, include a separate /reference option for each file.
alias
A valid C# identifier that will represent a root namespace that will contain all namespaces in the assembly.
Microsoft documentation page for cmd
From Visual Studio Community 2013 (Free version)
Right click References folder in your solution and browse for it there.
You are missing an assembly reference. Add a reference to System.Printing.dll.
You need to add the System.Printing assembly to your project.
You can find this by right clicking on your project and clicking "Add Reference". (You can search for it in the Assemblies > Framework tab)
Additionally, you must add using System.IO; in order to use Stream.
In your Solution Explorer right click on References click on Add Reference click on the .NET tab and scroll to System.Drawing. It should work.
Original answer found here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/0648fdc4-f67b-476e-b434-998efec14b89/class-systemprintingprintcapabilities-not-found?forum=wpf
However, you'll need to add the Assembly called ReachFramework

How to use DotNetZip

I've downloaded DotNetZip from codeplex and I am totally lost as to what to do next.
I want to extract a .zip archive
I know I use something like this
string zipToUnpack = "C1P3SML.zip";
string unpackDirectory = "Extracted Files";
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
foreach (ZipEntry e in zip1)
{
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
My question is, what project do I add and/or what references do I add?
Thanks
Just add a reference to Ionic.Zip.dll - you do need to make sure you are using the right reference for your target framework version (silverlight, WPF etc)
Then the above code should work assuming you import the Ionic namespace
Also not sure what you mean by 'what project should I add' - you already have a project right, or is this just a test project and you need to create a new project? If so any project type will do - but the best tests are either a console app or a forms/wpf app

Categories

Resources