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.
Related
I'm trying to publish a COM add-in for Word and need to have a license file. I'm using Rhino Licensing and the file has no issues during debugging, but when using OneClick to publish the add-in the license is reported as no longer valid. Here is the code for the class I'm using to check the license:
using System;
using System.IO;
using Rhino.Licensing;
namespace Services.Licensing
{
public class LicenseChecker
{
private static string PublicKeyPath;
private static string LicensePath;
public static bool LicenseIsValid(string licPath)
{
bool result = false;
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
String Root = Directory.GetCurrentDirectory();
PublicKeyPath = Root + #"\Licensing\publicKey.xml";
LicensePath = Root + #"\Licensing\license.xml"; //licPath;
// not working on INSTALL, runs fine in debug
try
{
var publicKey = File.ReadAllText(PublicKeyPath);
//Throws an exception if license has been modified
LicenseValidator validator = new LicenseValidator(publicKey, LicensePath);
validator.AssertValidLicense();
if (validator.ExpirationDate > DateTime.Now)
{
result = true;
}
}
catch
{ }
return result;
}
}
}
I'm trying to bundle the license with the exe I'll be giving to a small testing group to save the testers unnecessary trouble managing the license and public key. Currently I have the (valid) license file and public key as embedded resources, set to "copy always."
I'm having the same issue when the license is not bundled with the published exe, but the public key is. When both files are left outside of the solution, there seems to be no problem. Could publishing the solution be changing the byte array of the public key or the license?
I'm using .Net Framework 4.7.2 and Visual Studio 2019.
After a lot of toying, the broad answer seems to be no, ClickOnce publishing does not affect the byte array.
The error seems to be occurring because the ClickOnce is not copying XML files into the Application Files folder it creates at all.
After pulling the licenses into a desktop folder and having the program call them from there, another class that uses XML files to load list items would not initialize, leading me to put Try{} around all functions that use pre-made XML files in my program. Each of these functions returned the Catch{}. I'm assuming that ClickOnce is too simplistic an installer to be used if you are trying to include many/any resource files, especially if they are XML.
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
I am designing an application to run on the Microsoft HoloLens using Unity for the user interaction.
The application connects to an asmx webservice to retrieve data.
I have a C# test program to test the connection and data retrieval from the webservice.
I then followed this tutorial to generate a dll based on the webservice wsdl (https://www.youtube.com/watch?v=AifcMzEbKnA)
If use the following script to generate the dll:
#echo off
if exist "Service.xml" (
del MyOwnWS.wsdl
echo Rename
rename Service.xml MyOwnWS.wsdl
echo.
)
echo WSDL
call wsdl MyOwnWS.wsdl -o:MyOwnWS.cs
echo.
echo DMCS
call dmcs /target:library MyOwnWS.cs -r:System.Web.Services,System.Data
echo.
echo Done
I added system.Data because my webservice returns DataSet data from a Database.
I dropped that dll in the Assets folder of the Unity project.
I also had to drop System.Data.dll, System.dll, and System.Web.Services.dll in it (took them from C:\Program Files\Unity Hololens 5.4.0b16-HTP\Editor\Data\Mono\lib\mono\unity folder)
When I use the Unity editor, my application connects to the webservice and retrieve the data without problems.
Next step, I followed this tutorial to make a HoloLens application from Unity (http://hololenshelpwebsite.com/Blog/EntryId/1006/HoloLens-Hello-World)
While it work for their own Hello World, when I tried to build my own project from unity I receive the following error:
error CS1703: Multiple assemblies with equivalent identity have been
imported:
'C:\Users\UserA\.nuget\packages\Microsoft.NETCore.Portable.Compatibility\1.0.0\ref\netcore50\System.dll'
and 'J:\Work\MyTestUnity\Assets\System.dll'. Remove one of the
duplicate references.Copyright (C) Microsoft Corporation. All rights
reserved.Microsoft (R) Visual C# Compiler version 1.3.1.60616
So I added a ProjectFileHook.cs file under Editor with the following content:
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using UnityEditor;
using SyntaxTree.VisualStudio.Unity.Bridge;
using UnityEngine;
// http://forum.unity3d.com/threads/missing-c-references-to-system-data.11361/
// https://visualstudiogallery.msdn.microsoft.com/8d26236e-4a64-4d64-8486-7df95156aba9
[InitializeOnLoad]
public class ProjectFileHook
{
// necessary for XLinq to save the xml project file in utf8
class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
static void ProcessNodesWithIncludeAttribute(XDocument document, string localName, string includeValue, Action<XElement> action)
{
var nodes = document
.Descendants()
.Where(p => p.Name.LocalName == localName);
foreach (var node in nodes)
{
var xa = node.Attribute("Include");
if (xa != null && !string.IsNullOrEmpty(xa.Value) && string.Equals(xa.Value, includeValue))
{
action(node);
}
}
}
// Remove System.Data from project (not from file system so Unity can compile properly)
static void RemoveFileFromProject(XDocument document, string fileName)
{
ProcessNodesWithIncludeAttribute(document, "None", fileName, element => element.Remove());
}
// Adjust references, by using the default framework assembly instead of local file (remove the HintPath)
static void RemoveHintPathFromReference(XDocument document, string assemblyName)
{
ProcessNodesWithIncludeAttribute(document, "Reference", assemblyName, element => element.Nodes().Remove());
}
static ProjectFileHook()
{
ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
{
var document = XDocument.Parse(content);
RemoveFileFromProject(document, #"Assets\System.Data.dll");
RemoveHintPathFromReference(document, "System.Data");
RemoveFileFromProject(document, #"Assets\System.Web.Services.dll");
RemoveHintPathFromReference(document, "System.Web.Services");
RemoveFileFromProject(document, #"Assets\System.dll");
RemoveHintPathFromReference(document, "System");
var str = new Utf8StringWriter();
document.Save(str);
return str.ToString();
};
}
}
But it looks like this does nothing.
I am at a lost about how to fix this at the moment, and I really need experts help to figure it out.
So...
It looks like we cannot use WSDL webservice like that anymore.
Microsoft dropped the support for it in an update no so long ago.
I saw multiple articles about it, but I forgot to keep a bookmark.
So if you want look it up, you will have to go through the WUP documentation.
Instead we ended up using UnityWebRequest and Coroutines to handle the webservice communication.
We also had to update the webservice to enable Get/post calls.
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
I'm developing in Visual Studio 2010 and I've just downloaded and installed Script# 0.6.2 for VS 2010. I'm trying to follow the clock example in the Read Me pdf but can't get it to compile.
I've created a new Script# Class Library project inside my solution called Clock, renamed the .cs file to ClockBehaviour and added the following code as per the example:
using System;
using System.DHTML;
using ScriptFX;
using ScriptFX.UI;
namespace Clock {
public class ClockBehavior : Behavior {
private int _intervalCookie;
public ClockBehavior(DOMElement domElement, string id) : base(domElement, id) {
_intervalCookie = Window.SetInterval(OnTimer, 1000);
}
public override void Dispose() {
if (_intervalCookie != 0) {
Window.ClearInterval(_intervalCookie);
} base.Dispose();
} private void OnTimer() { DateTime dateTime = new DateTime(); DOMElement.InnerHTML = dateTime.Format("T"); }
}
}
When I try and compile the project I get errors saying that the System.DHMTL, ScriptFX and ScriptFX.UI namespaces could not be found (and some others, but I guess by fixing these errors the others will fall out).
It feels like I'm not referencing the correct projects/dlls. In the References for the project I have mscorlib and Script.Web. I've tried using the object browser find the classes (such as Behavior) in other namespaces but with no luck. I've added all of the .dlls from the ScriptSharp folder in Program Files but the namespaces still can't be found.
Any help would be very much appreciated,
Thanks,
Hugh
the sample docs are a bit out of date - look at the phot sample in the samples download : http://projects.nikhilk.net/Content/Projects/ScriptSharp/Sample.zip
See http://projects.nikhilk.net/ScriptSharp/Conceptual-What
You need to reference ssfx.Core.dll which should be installed with Script#
(Alternatively, see pp 23-24 of the pdf you linked...)