Dispose() protected method

Closes the zip input stream
protected Dispose ( bool disposing ) : void
disposing bool
return void
Beispiel #1
0
 /// <summary>
 /// 解压缩
 /// </summary>
 /// <param name="zipBytes">待解压数据</param>
 /// <returns></returns>
 public static byte[] UnZip(byte[] zipBytes)
 {
     ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = null;
     ICSharpCode.SharpZipLib.Zip.ZipEntry       ent       = null;
     byte[] reslutBytes = null;
     try
     {
         using (System.IO.MemoryStream inputZipStream = new System.IO.MemoryStream(zipBytes))
         {
             zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(inputZipStream);
             if ((ent = zipStream.GetNextEntry()) != null)
             {
                 reslutBytes = new byte[zipStream.Length];
                 zipStream.Read(reslutBytes, 0, reslutBytes.Length);
             }
         }
     }
     finally
     {
         if (zipStream != null)
         {
             zipStream.Close();
             zipStream.Dispose();
         }
         if (ent != null)
         {
             ent = null;
         }
         GC.Collect();
         GC.Collect(1);
     }
     return(reslutBytes);
 }
    public override Stream GetInputStream(UploadedFile file)
    {
        FileStream fileS = null;
        ZipInputStream zipS = null;

        try
        {
            string path = GetZipPath(file);

            fileS = File.OpenRead(path);
            zipS = new ZipInputStream(fileS);

            zipS.GetNextEntry();

            return zipS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();

            if (zipS != null)
                zipS.Dispose();

            return null;
        }
    }
Beispiel #3
0
        public static bool UnPackFiles(string path, string filePath)
        {
            try
            {

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = Path.GetDirectoryName(path);
                ZipInputStream zstream = new ZipInputStream(File.OpenRead(filePath));
                ZipEntry entry;
                while ((entry = zstream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(entry.Name))
                    {
                        string upath = path + "\\" + entry.Name;
                        if (entry.IsDirectory)
                        {
                            Directory.CreateDirectory(upath);
                        }
                        else if (entry.CompressedSize > 0)
                        {
                            FileStream fs = File.Create(upath);
                            int size = 2048;
                            byte[] data = new byte[size];
                            while (true)
                            {
                                size = zstream.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    fs.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            fs.Dispose();
                            fs.Close();
                        }
                    }
                }
                zstream.Dispose();
                zstream.Close();
                return true;
            }
            catch
            {
                throw;
            }

        }
 private static Stream OpenFirstZipEntry(Stream rawStream)
 {
     var zipStream = new ZipInputStream(rawStream);
     try
     {
         zipStream = new ZipInputStream(rawStream);
         zipStream.GetNextEntry();
         return zipStream;
     }
     catch
     {
         zipStream.Dispose();
         throw;
     }
 }
        public static int Extract(string sourceFile, string destinationPath)
        {
            ZipInputStream zinstream = null; // used to read from the zip file
            int numFileUnzipped = 0; // number of files extracted from the zip file

            try
            {
                // create a zip input stream from source zip file
                zinstream = new ZipInputStream(File.OpenRead(sourceFile));

                // we need to extract to a folder so we must create it if needed
                if (Directory.Exists(destinationPath) == false)
                    Directory.CreateDirectory(destinationPath);

                ZipEntry theEntry; // an entry in the zip file which could be a file or directory

                // now, walk through the zip file entries and copy each file/directory
                while ((theEntry = zinstream.GetNextEntry()) != null)
                {
                    string dirname = Path.GetDirectoryName(theEntry.Name); // the file path
                    string fname = Path.GetFileName(theEntry.Name);      // the file name

                    // if a path name exists we should create the directory in the destination folder
                    string target = destinationPath + Path.DirectorySeparatorChar + dirname;
                    if (dirname.Length > 0 && !Directory.Exists(target))
                        Directory.CreateDirectory(target);

                    // now we know the proper path exists in the destination so copy the file there
                    if (fname != String.Empty)
                    {
                        DecompressAndWriteFile(destinationPath + Path.DirectorySeparatorChar + theEntry.Name, zinstream);
                        numFileUnzipped++;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                zinstream.Dispose();
                zinstream.Close();
            }
            return numFileUnzipped;
        }
        public override Stream GetReadStream(UploadedFile file)
        {
            FileStream fileS = null;
            ZipInputStream zipS = null;

            try
            {
                fileS = File.OpenRead(file.ServerLocation);
                zipS = new ZipInputStream(fileS);

                zipS.GetNextEntry();

                return zipS;
            }
            catch
            {
                if (zipS != null)
                    zipS.Dispose();
                if (fileS != null)
                    fileS.Dispose();

                throw;
            } 
        }
 /// <summary>
 /// Create a temporary XML file that will be send to SAP application
 /// </summary>
 /// <param name="m"></param>
 /// <param name="filePath"></param>
 internal void Deserialize(string filePath)
 {
     Stream stream = new MemoryStream();
     System.Windows.Forms.Cursor cursor = System.Windows.Forms.Cursor.Current;
     try
     {
         byte[] buffer = new byte[8192];
         if (".xml".Equals(Path.GetExtension(filePath).ToLower()))
         {
             FileStream fReader = File.OpenRead(filePath);
             Deserialize(fReader);
             fReader.Close();
         }
         else
         {
             FileStream fs = File.OpenRead(filePath);
             BinaryFormatter bformatter = new BinaryFormatter();
             string version = (string)bformatter.Deserialize(fs); //"version=7.14"
             if ("version=7.14".CompareTo(version) > 0)
             {
                 fs.Close();
                 string translate = System.Windows.Forms.Application.StartupPath + "\\Translate.exe";
                 if (File.Exists(translate))
                 {
                     string msg = string.Format("El archivo {0} es para una versión anterior de Treu Structure. ¿Desea traducirlo a la versión actual? Se guardará una copia del original en {0}.bak", filePath);
                     System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show(msg,
                         "Actualización", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question);
                     if (result == System.Windows.Forms.DialogResult.Yes)
                     {
                         System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo(translate);
                         start.Arguments = "\"" + filePath + "\"";
                         start.UseShellExecute = false;
                         start.RedirectStandardOutput = true;
                         System.Diagnostics.Process p = System.Diagnostics.Process.Start(start);
                         p.WaitForExit(60000);
                         string output = p.StandardOutput.ReadToEnd();
                         if (p.HasExited && p.ExitCode == 0)
                             Deserialize(filePath);
                         else
                         {
                             msg = "Ocurrió un error y no se pudo actualizar el archivo. Favor de contactar a Soporte Técnico o a [email protected]";
                             System.Windows.Forms.MessageBox.Show(msg, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                         }
                     }
                     else
                         throw new Exception("File cannot be opened");
                 }
                 else
                     throw new Exception("File cannot be opened");
             }
             else
             {
                 System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                 using (ZipInputStream s = new ZipInputStream(fs))
                 {
                     try
                     {
                         s.Password = "******";
                         if (s.GetNextEntry() != null)
                         {
                             StreamUtils.Copy(s, stream, buffer);
                             stream.Position = 0;
                             Deserialize(stream);
                         }
                     }
                     finally
                     {
                         s.Close();
                         s.Dispose();
                     }
                 }
             }
         }
     }
     finally
     {
         stream.Close();
         System.Windows.Forms.Cursor.Current = cursor;
     }
 }
Beispiel #8
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="unPackToPath">解压到哪个绝对路径下</param>
 /// <param name="packFilePath">要解压的文件的路径</param>
 /// <param name="packFileName">要解压的文件名</param>
 /// <returns></returns>
 public static bool UnPackFiles(string unPackToPath, string packFilePath, string packFileName)
 {
     try
     {
         if (!Directory.Exists(unPackToPath))
         {
             Directory.CreateDirectory(unPackToPath);
         }
         //unPackToPath = Path.GetDirectoryName(unPackToPath);
         string filepath = Path.Combine(packFilePath, packFileName);
         ZipInputStream zstream = new ZipInputStream(File.OpenRead(filepath));
         ZipEntry entry;
         while ((entry = zstream.GetNextEntry()) != null)
         {
             if (!string.IsNullOrEmpty(entry.Name))
             {
                 string upath = (unPackToPath + "\\" + entry.Name).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                 string direct=Path.GetDirectoryName(upath);
                 if (!Directory.Exists(direct))
                 {
                     Directory.CreateDirectory(direct);
                 }
                 if (entry.IsDirectory)
                 {
                     Directory.CreateDirectory(upath);
                 }
                 else if (entry.IsFile)
                 {
                     FileStream fs = File.Create(upath);
                     int size = 2048;
                     byte[] data = new byte[size];
                     while (true)
                     {
                         size = zstream.Read(data, 0, data.Length);
                         if (size > 0)
                         {
                             fs.Write(data, 0, size);
                         }
                         else
                         {
                             break;
                         }
                     }
                     fs.Dispose();
                     fs.Close();
                 }
             }
         }
         zstream.Dispose();
         zstream.Close();
         return true;
     }
     catch
     {
         throw;
     }
 }
        private void BindGrid(string installPath, DataGrid grid)
        {
            var packages = new List<PackageInfo>();
            var invalidPackages = new List<string>();

            foreach (string file in Directory.GetFiles(installPath))
            {
                if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources"))
                {
                    Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                    var unzip = new ZipInputStream(inputStream);

                    try
                    {
                        ZipEntry entry = unzip.GetNextEntry();

                        while (entry != null)
                        {
                            if (!entry.IsDirectory)
                            {
                                var fileName = entry.Name;
                                string extension = System.IO.Path.GetExtension(fileName);
                                if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5")
                                {
                                    //Manifest
                                    var manifestReader = new StreamReader(unzip);
                                    var manifest = manifestReader.ReadToEnd();

                                    var package = new PackageInfo();
                                    package.Manifest = manifest;
                                    if (!string.IsNullOrEmpty(manifest))
                                    {
                                        var doc = new XPathDocument(new StringReader(manifest));
                                        XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke");
                                        string packageType = String.Empty;
                                        if (rootNav.Name == "dotnetnuke")
                                        {
                                            packageType = XmlUtils.GetAttributeValue(rootNav, "type");
                                        }
                                        else if (rootNav.Name.ToLower() == "languagepack")
                                        {
                                            packageType = "LanguagePack";
                                        }
                                        XPathNavigator nav = null;
                                        switch (packageType.ToLower())
                                        {
                                            case "package":
                                                nav = rootNav.SelectSingleNode("packages/package");
                                                break;
                                            case "module":
                                            case "languagepack":
                                            case "skinobject":
                                                nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package");
                                                break;
                                        }

                                        if (nav != null)
                                        {
                                            package.Name = XmlUtils.GetAttributeValue(nav, "name");
                                            package.PackageType = XmlUtils.GetAttributeValue(nav, "type");
                                            package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false);
                                            package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version"));
                                            package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName");
                                            if (String.IsNullOrEmpty(package.FriendlyName))
                                            {
                                                package.FriendlyName = package.Name;
                                            }
                                            package.Description = XmlUtils.GetNodeValue(nav, "description");
                                            package.FileName = file.Replace(installPath + "\\", "");

                                            XPathNavigator foldernameNav = null;
                                            switch (package.PackageType)
                                            {
                                                case "Module":
                                                case "Auth_System":
                                                    foldernameNav = nav.SelectSingleNode("components/component/files");
                                                    if (foldernameNav != null) package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/');
                                                    break;
                                                case "Container":
                                                    foldernameNav = nav.SelectSingleNode("components/component/containerFiles");
                                                    if (foldernameNav != null) package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/');
                                                    break;
                                                case "Skin":
                                                    foldernameNav = nav.SelectSingleNode("components/component/skinFiles");
                                                    if (foldernameNav != null) package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/');
                                                    break;
                                                default:
                                                    break;
                                            }

                                            XPathNavigator iconFileNav = nav.SelectSingleNode("iconFile");
                                            if (package.FolderName != string.Empty && iconFileNav != null)
                                            {

                                                if ((iconFileNav.Value != string.Empty) && (package.PackageType == "Module" || package.PackageType == "Auth_System" || package.PackageType == "Container" || package.PackageType == "Skin"))
                                                {
                                                    package.IconFile = package.FolderName + "/" + iconFileNav.Value;
                                                    package.IconFile = (!package.IconFile.StartsWith("~/")) ? "~/" + package.IconFile : package.IconFile;
                                                }
                                            }

                                            packages.Add(package);
                                        }
                                    }

                                    break;
                                }
                            }
                            entry = unzip.GetNextEntry();
                        }
                    }
                    catch (Exception)
                    {
                        invalidPackages.Add(file);
                    }
                    finally
                    {
                        unzip.Close();
                        unzip.Dispose();
                    }
                }
            }

            if (invalidPackages.Count > 0)
            {
                var pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />"));
                UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError);
            }

            grid.DataSource = packages;
            grid.DataBind();
        }
Beispiel #10
0
        public static void UnzipResources(ZipInputStream zipStream, string destPath)
        {
            try
            {
                ZipEntry objZipEntry;
                string LocalFileName;
                string RelativeDir;
                string FileNamePath;
                objZipEntry = zipStream.GetNextEntry();
                while (objZipEntry != null)
                {
                    LocalFileName = objZipEntry.Name;
                    RelativeDir = Path.GetDirectoryName(objZipEntry.Name);
                    if ((RelativeDir != string.Empty) && (!Directory.Exists(Path.Combine(destPath, RelativeDir))))
                    {
                        Directory.CreateDirectory(Path.Combine(destPath, RelativeDir));
                    }
                    if ((!objZipEntry.IsDirectory) && (!String.IsNullOrEmpty(LocalFileName)))
                    {
                        FileNamePath = Path.Combine(destPath, LocalFileName).Replace("/", "\\");
                        try
                        {
                            if (File.Exists(FileNamePath))
                            {
                                File.SetAttributes(FileNamePath, FileAttributes.Normal);
                                File.Delete(FileNamePath);
                            }
                            FileStream objFileStream = null;
                            try
                            {
                                objFileStream = File.Create(FileNamePath);
                                int intSize = 2048;
                                var arrData = new byte[2048];
                                intSize = zipStream.Read(arrData, 0, arrData.Length);
                                while (intSize > 0)
                                {
                                    objFileStream.Write(arrData, 0, intSize);
                                    intSize = zipStream.Read(arrData, 0, arrData.Length);
                                }
                            }
                            finally
                            {
                                if (objFileStream != null)
                                {
                                    objFileStream.Close();
                                    objFileStream.Dispose();
                                }
                            }
                        }
                        catch(Exception ex)
                        {
							DnnLog.Error(ex);
                        }
                    }
                    objZipEntry = zipStream.GetNextEntry();
                }
            }
            finally
            {
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
            }
        }
		private static bool InitializeIcuData()
		{
			var icuDir = Icu.DefaultDirectory;
			ZipInputStream zipIn = null;
			try
			{
				try
				{
					var baseDir = FwDirectoryFinder.DataDirectory;
					zipIn = new ZipInputStream(File.OpenRead(Path.Combine(baseDir, string.Format("Icu{0}.zip", Icu.Version))));
				}
				catch (Exception e1)
				{
					MessageBoxUtils.Show("Something is wrong with the file you chose." + Environment.NewLine +
						" The file could not be opened. " + Environment.NewLine + Environment.NewLine +
						"   The error message was: '" + e1.Message);
				}
				if (zipIn == null)
					return false;
				Icu.Cleanup();
				foreach (string dir in Directory.GetDirectories(icuDir))
				{
					string subdir = Path.GetFileName(dir);
					if (subdir.Equals(string.Format("icudt{0}l", Icu.Version), StringComparison.OrdinalIgnoreCase))
						Directory.Delete(dir, true);
				}
				ZipEntry entry;
				while ((entry = zipIn.GetNextEntry()) != null)
				{
					string dirName = Path.GetDirectoryName(entry.Name);
					Match match = Regex.Match(dirName, @"^ICU\d\d[\\/]?(.*)$", RegexOptions.IgnoreCase);
					if (match.Success) // Zip file was built in a way that includes the root directory name.
						dirName = match.Groups[1].Value; // Strip it off. May leave empty string.
					string fileName = Path.GetFileName(entry.Name);
					bool fOk = UnzipFile(zipIn, fileName, entry.Size, Path.Combine(icuDir, dirName));
					if (!fOk)
						return false;
				}
				return true;
			}
			finally
			{
				if (zipIn != null)
					zipIn.Dispose();
			}
		}
        private void BindGrid(string type, DataGrid grid, HtmlGenericControl noItemsControl)
        {
            var installPath = Globals.ApplicationMapPath + "\\Install\\" + type;
            var packages = new List<PackageInfo>();
            var invalidPackages = new List<string>();

            foreach (string file in Directory.GetFiles(installPath))
            {
                if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources"))
                {
                    Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                    var unzip = new ZipInputStream(inputStream);

                    try
                    {
                        ZipEntry entry = unzip.GetNextEntry();

                        while (entry != null)
                        {
                            if (!entry.IsDirectory)
                            {
                                var fileName = entry.Name;
                                string extension = Path.GetExtension(fileName);
                                if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5")
                                {
                                    //Manifest
                                    var manifestReader = new StreamReader(unzip);
                                    var manifest = manifestReader.ReadToEnd();

                                    var package = new PackageInfo();
                                    package.Manifest = manifest;
                                    if (!string.IsNullOrEmpty(manifest))
                                    {
                                        var doc = new XPathDocument(new StringReader(manifest));
                                        XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke");
                                        string packageType = String.Empty;
                                        if (rootNav.Name == "dotnetnuke")
                                        {
                                            packageType = XmlUtils.GetAttributeValue(rootNav, "type");
                                        }
                                        else if (rootNav.Name.ToLower() == "languagepack")
                                        {
                                            packageType = "LanguagePack";
                                        }
                                        XPathNavigator nav = null;
                                        switch (packageType.ToLower())
                                        {
                                            case "package":
                                                nav = rootNav.SelectSingleNode("packages/package");
                                                break;

                                            case "languagepack":

                                                //nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package");
                                                break;
                                        }

                                        if (nav != null)
                                        {
                                            package.Name = XmlUtils.GetAttributeValue(nav, "name");
                                            package.PackageType = XmlUtils.GetAttributeValue(nav, "type");
                                            package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false);
                                            package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version"));
                                            package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName");
                                            if (String.IsNullOrEmpty(package.FriendlyName))
                                            {
                                                package.FriendlyName = package.Name;
                                            }

                                            package.Description = XmlUtils.GetNodeValue(nav, "description");
                                            package.FileName = file.Replace(installPath + "\\", "");

                                            packages.Add(package);
                                        }
                                    }

                                    break;
                                }
                            }
                            entry = unzip.GetNextEntry();
                        }
                    }
                    catch (Exception)
                    {
                        invalidPackages.Add(file);
                    }
                    finally
                    {
                        unzip.Close();
                        unzip.Dispose();
                    }
                }
            }

            if (invalidPackages.Count > 0)
            {
                var pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />"));
                Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError);
            }

            if (packages.Count == 0)
            {
                noItemsControl.Visible = true;
                grid.Visible = false;    
            }
            else
            {
                noItemsControl.Visible = false;
                grid.DataSource = packages;
                grid.DataBind();
            }            
        }
Beispiel #13
0
    /// <summary> 
    /// 解压功能(解压压缩文件到指定目录) 
    /// </summary> 
    /// <param name="fileToUnZip">待解压的文件</param> 
    /// <param name="zipedFolder">指定解压目标目录</param> 
    /// <param name="password">密码</param> 
    /// <returns>解压结果</returns> 
    public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
    {
        bool result = true;
        FileStream fs = null;
        ZipInputStream zipStream = null;
        ZipEntry ent = null;
        string fileName;

        if (!File.Exists(fileToUnZip))
            return false;

        if (!Directory.Exists(zipedFolder))
            Directory.CreateDirectory(zipedFolder);

        try
        {
            zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
            if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
            while ((ent = zipStream.GetNextEntry()) != null)
            {
                if (!string.IsNullOrEmpty(ent.Name))
                {
                    fileName = Path.Combine(zipedFolder, ent.Name);
//                    fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi 

                    if (fileName.EndsWith("/"))
                    {
                        Directory.CreateDirectory(fileName);
                        continue;
                    }

                    fs = File.Create(fileName);
                    int size = 2048;
                    byte[] data = new byte[size];
                    while (true)
                    {
                        size = zipStream.Read(data, 0, data.Length);
                        if (size > 0)
                            fs.Write(data, 0, size); ///< data.Length
                        else
                            break;
                    }
                }
            }
        }
        catch
        {
            result = false;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
                fs.Dispose();
            }
            if (zipStream != null)
            {
                zipStream.Close();
                zipStream.Dispose();
            }
            if (ent != null)
            {
                ent = null;
            }
            GC.Collect();
            GC.Collect(1);
        }
        return result;
    }
        private void BindGrid(string installPath, DataGrid grid)
        {
            var packages = new List<PackageInfo>();
            var invalidPackages = new List<string>();

            foreach (string file in Directory.GetFiles(installPath))
            {
                if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources"))
                {
                    Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                    var unzip = new ZipInputStream(inputStream);

                    try
                    {
                        ZipEntry entry = unzip.GetNextEntry();

                        while (entry != null)
                        {
                            if (!entry.IsDirectory)
                            {
                                string fileName = entry.Name;
                                string extension = Path.GetExtension(fileName);
                                if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5")
                                {
                                    //Manifest
                                    var manifestReader = new StreamReader(unzip);
                                    string manifest = manifestReader.ReadToEnd();

                                    var package = new PackageInfo();
                                    package.Manifest = manifest;
                                    if (!string.IsNullOrEmpty(manifest))
                                    {
                                        var doc = new XPathDocument(new StringReader(manifest));
                                        XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke");
                                        string packageType = String.Empty;
                                        if (rootNav.Name == "dotnetnuke")
                                        {
                                            packageType = XmlUtils.GetAttributeValue(rootNav, "type");
                                        }
                                        else if (rootNav.Name.ToLower() == "languagepack")
                                        {
                                            packageType = "LanguagePack";
                                        }
                                        XPathNavigator nav = null;
                                        switch (packageType.ToLower())
                                        {
                                            case "package":
                                                nav = rootNav.SelectSingleNode("packages/package");
                                                break;

                                            case "languagepack":

                                                nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package");
                                                break;
                                        }

                                        if (nav != null)
                                        {
                                            package.Name = XmlUtils.GetAttributeValue(nav, "name");
                                            package.PackageType = XmlUtils.GetAttributeValue(nav, "type");
                                            package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false);
                                            package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version"));
                                            package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName");
                                            if (String.IsNullOrEmpty(package.FriendlyName))
                                            {
                                                package.FriendlyName = package.Name;
                                            }
                                            package.Description = XmlUtils.GetNodeValue(nav, "description");
                                            package.FileName = file.Replace(installPath + "\\", "");

                                            packages.Add(package);
                                        }
                                    }

                                    break;
                                }
                            }
                            entry = unzip.GetNextEntry();
                        }
                    }
                    catch (Exception)
                    {
                        invalidPackages.Add(file);
                    }
                    finally
                    {
                        unzip.Close();
                        unzip.Dispose();
                    }
                }
            }

            //now add language packs from update service
            try
            {
                StreamReader myResponseReader = UpdateService.GetLanguageList();
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(myResponseReader);
                XmlNodeList languages = xmlDoc.SelectNodes("available/language");

                if (languages != null)
                {
	                var installedPackages = PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "CoreLanguagePack");
	                var installedLanguages = installedPackages.Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID)).ToList();
	                foreach (XmlNode language in languages)
                    {
                        string cultureCode = "";
                        string version = "";
                        foreach (XmlNode child in language.ChildNodes)
                        {
                            if (child.Name == "culturecode")
                            {
                                cultureCode = child.InnerText;
                            }

                            if (child.Name == "version")
                            {
                                version = child.InnerText;
                            }
                        }
	                    if (!string.IsNullOrEmpty(cultureCode) && !string.IsNullOrEmpty(version) && version.Length == 6)
	                    {
		                    var myCIintl = new CultureInfo(cultureCode, true);
		                    version = version.Insert(4, ".").Insert(2, ".");
		                    var package = new PackageInfo {Owner = OwnerUpdateService, Name = "LanguagePack-" + myCIintl.Name, FriendlyName = myCIintl.NativeName};
		                    package.Name = myCIintl.NativeName;
		                    package.Description = cultureCode;
		                    Version ver = null;
		                    Version.TryParse(version, out ver);
		                    package.Version = ver;

							if (
								installedLanguages.Any(
									l =>
									LocaleController.Instance.GetLocale(l.LanguageID).Code.ToLowerInvariant().Equals(cultureCode.ToLowerInvariant()) 
									&& installedPackages.First(p => p.PackageID == l.PackageID).Version >= ver))
							{
								continue;
							}

							if (packages.Any(p => p.Name == package.Name))
							{
								var existPackage = packages.First(p => p.Name == package.Name);
								if (package.Version > existPackage.Version)
								{
									packages.Remove(existPackage);
									packages.Add(package);
								}
							}
							else
							{
								packages.Add(package);
							}
	                    }
                    }
                }
            }
            catch (Exception)
            {
                //suppress for now - need to decide what to do when webservice is unreachable
                //throw;
                //same problem happens in InstallWizard.aspx.cs in BindLanguageList method
            }


            if (invalidPackages.Count > 0)
            {
                string pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />"));
                Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError);
            }

            grid.DataSource = packages;
            grid.DataBind();
        }
Beispiel #15
0
        static XmlReaderSettings GetSettings(String release)
        {

            XmlReaderSettings retVal = null;
            if (ValidationSettings.TryGetValue(release, out retVal))
                return retVal;

            string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tmpDir);

            Assembly asm = typeof(XMLValidator).Assembly;

            try
            {
                foreach (var item in asm.GetManifestResourceNames())
                {
                    if (!item.EndsWith("zip"))
                        continue;

                    string itemRelease = item.Replace("MARC.Everest.Test.Resources.", "").Replace(".zip", "");
                    if (itemRelease != release)
                        continue;

                    ZipInputStream zis = null;
                    Tracer.Trace(item);

                    try
                    {
                        zis = new ZipInputStream(asm.GetManifestResourceStream(item));
                        retVal = new XmlReaderSettings();

                        // Prepare the unzipping operation
                        ZipEntry entry = null;
                        String basePath = Path.Combine(tmpDir, item);
                        if (!Directory.Exists(basePath))
                            Directory.CreateDirectory(basePath);

                        List<String> files = new List<string>(10);

                        // Unzip the rmim package
                        while ((entry = zis.GetNextEntry()) != null)
                        {
                            if (entry.IsDirectory) // entry is a directory
                            {
                                string dirName = Path.Combine(basePath, entry.Name);
                                if (!Directory.Exists(dirName))
                                    Directory.CreateDirectory(dirName);
                            }
                            else if (entry.IsFile) // entry is file, so extract file.
                            {
                                string fName = Path.Combine(basePath, entry.Name);
                                FileStream fs = null;
                                try
                                {
                                    fs = File.Create(fName);
                                    byte[] buffer = new byte[2048]; // 2k buffer
                                    int szRead = 2048;
                                    while (szRead > 0)
                                    {
                                        szRead = zis.Read(buffer, 0, buffer.Length);
                                        if (szRead > 0)
                                            fs.Write(buffer, 0, szRead);
                                    }
                                }
                                finally
                                {
                                    if (fs != null)
                                        fs.Close();
                                }

                                if (fName.EndsWith(".xsd"))
                                    files.Add(fName);
                            }
                        }

                        foreach (var fName in files)
                            retVal.Schemas.Add("urn:hl7-org:v3", fName);

                        retVal.Schemas.ValidationEventHandler += new ValidationEventHandler(Schemas_ValidationEventHandler);
                        retVal.Schemas.Compile();
                        ValidationSettings.Add(release, retVal);
                        Directory.Delete(basePath, true);
                        return retVal;
                    }
                    catch (Exception e)
                    {
                        //Assert.Fail(e.ToString());
                        return retVal;
                    }
                    finally
                    {
                        if (zis != null)
                        {
                            zis.Close();
                            zis.Dispose();
                        }
                    }

                }
            }
            finally
            {
                Directory.Delete(tmpDir, true);
                System.GC.Collect();
            }
            return retVal;
        }
Beispiel #16
0
        /// <summary> 
        /// 解压功能(解压压缩文件到指定目录) 
        /// </summary> 
        /// <param name="fileToUnZip">待解压的文件</param> 
        /// <param name="zipedFolder">指定解压目标目录</param> 
        /// <param name="password">密码</param> 
        /// <returns>解压结果</returns> 
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            bool result = true;
            FileStream fs = null;
            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            string fileName;

            if (!File.Exists(fileToUnZip))
                return false;

            if (!Directory.Exists(zipedFolder))
                Directory.CreateDirectory(zipedFolder);

            ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fileToUnZip);
            //zipfile.
            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi

                        if (fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        if (ent.Name == "config.json")
                        {
                            //Directory.CreateDirectory(fileName);
                            continue;
                        }

                        if (ent.IsFile)
                        {
                            //Directory.CreateDirectory(fileName);
                            if (!File.Exists(Common.BackupDicPath+ ent.Name))
                            {
                                FileInfo fi = new FileInfo(Common.MasterDicPath + ent.Name);
                                //fi.
                                string backuppath = (Common.BackupDicPath + ent.Name);
                                backuppath = backuppath.Remove(backuppath.LastIndexOf('/'));
                                if (!Directory.Exists(backuppath))
                                {
                                    Directory.CreateDirectory(backuppath);
                                }
                                File.Copy(Common.MasterDicPath + ent.Name, Common.BackupDicPath + ent.Name);
                            }
                            //continue;
                        }

                        fs = File.Create(fileName);
                        var s=zipfile.GetInputStream(ent);
                        //StreamWriter sw = new StreamWriter(fs);
                        //sw.Write()
                        int size = 2048;
                        byte[] data = new byte[size];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                                fs.Write(data, 0, data.Length);
                            else
                                break;
                        }
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }
Beispiel #17
0
        public static void UnZipFiles(string zipFilePath, string outputFolder, string password, bool deleteZipFile, string moveZipToFolder)
        {
            using (var s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                if (!string.IsNullOrEmpty(password))
                {
                    s.Password = password;
                }

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = outputFolder;
                    string fileName = Path.GetFileName(theEntry.Name);
                    // create directory
                    if (Helpers.DirectoryExist(directoryName))
                    {
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            if (theEntry.Name.IndexOf(".ini", System.StringComparison.Ordinal) < 0)
                            {
                                string fullPath = directoryName + "\\" + theEntry.Name;
                                fullPath = fullPath.Replace("\\ ", "\\");
                                string fullDirPath = Path.GetDirectoryName(fullPath);
                                if (fullDirPath != null && !Directory.Exists(fullDirPath))
                                {
                                    Directory.CreateDirectory(fullDirPath);
                                }

                                using (var streamWriter = File.Create(fullPath))
                                {
                                    int size = 2048;
                                    var data = new byte[size];
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);
                                        if (size > 0)
                                        {
                                            streamWriter.Write(data, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    streamWriter.Close();
                                }
                            }
                        }
                    }
                }

                s.Close();
                s.Dispose();
            }

            if (deleteZipFile)
            {
                File.Delete(zipFilePath);
            }

            if (!string.IsNullOrEmpty(moveZipToFolder) && Helpers.DirectoryExist(moveZipToFolder))
            {
                string zipName = zipFilePath.Split('\\').Last();
                File.Move(zipFilePath, moveZipToFolder + "\\" + zipName);
            }
        }
Beispiel #18
0
        Image ReadApkIcon(string path)
        {
            Image img = null;

            try
            {
                FileStream fs = File.Open(path, FileMode.Open);
                if (fs == null)
                    return img;
                ZipInputStream zipStream = new ZipInputStream(fs);
                ZipEntry entry = zipStream.GetNextEntry();
                while (entry != null)
                {
                    if (!entry.IsFile)
                    {
                        continue;
                    }
                    if (entry.Name.EndsWith("drawable/ic_launcher.png")
                        || entry.Name.EndsWith("drawable/icon.png")
                        || entry.Name.EndsWith("dpi/ic_launcher.png")
                        || entry.Name.EndsWith("dpi/icon.png"))
                    {
                        FileStream writer = File.Create(GlobalSys.tmpIconPath);//解压后的文件

                        int bufferSize = 1024; //缓冲区大小
                        int readCount = 0; //读入缓冲区的实际字节
                        byte[] buffer = new byte[bufferSize];
                        readCount = zipStream.Read(buffer, 0, bufferSize);
                        while (readCount > 0)
                        {
                            writer.Write(buffer, 0, readCount);
                            readCount = zipStream.Read(buffer, 0, bufferSize);
                        }

                        writer.Close();
                        writer.Dispose();
                        Bitmap bmp = new Bitmap(GlobalSys.tmpIconPath);
                        img = new Bitmap(bmp);
                        bmp.Dispose(); bmp = null;
                        break;
                    }
                    entry = zipStream.GetNextEntry();
                }
                fs.Close();
                zipStream.Close();
                zipStream.Dispose();
                zipStream = null;
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }

            return img;
        }
 public static string UnzipFile(string fileName, string DestFolder, PortalSettings settings)
 {
     ZipInputStream objZipInputStream = null;
     string strMessage = "";
     try
     {
         int FolderPortalId = GetFolderPortalId(settings);
         bool isHost = settings.ActiveTab.ParentId == settings.SuperTabId;
         PortalController objPortalController = new PortalController();
         CommonLibrary.Services.FileSystem.FolderController objFolderController = new CommonLibrary.Services.FileSystem.FolderController();
         CommonLibrary.Services.FileSystem.FileController objFileController = new CommonLibrary.Services.FileSystem.FileController();
         string sourceFolderName = Globals.GetSubFolderPath(fileName, FolderPortalId);
         string sourceFileName = GetFileName(fileName);
         CommonLibrary.Services.FileSystem.FolderInfo folder = objFolderController.GetFolder(FolderPortalId, sourceFolderName, false);
         CommonLibrary.Services.FileSystem.FileInfo file = objFileController.GetFile(sourceFileName, FolderPortalId, folder.FolderID);
         int storageLocation = folder.StorageLocation;
         ZipEntry objZipEntry;
         string strFileName = "";
         string strExtension;
         try
         {
             objZipInputStream = new ZipInputStream(GetFileStream(file));
         }
         catch (Exception ex)
         {
             return ex.Message;
         }
         ArrayList sortedFolders = new ArrayList();
         objZipEntry = objZipInputStream.GetNextEntry();
         while (objZipEntry != null)
         {
             if (objZipEntry.IsDirectory)
             {
                 try
                 {
                     sortedFolders.Add(objZipEntry.Name.ToString());
                 }
                 catch (Exception ex)
                 {
                     objZipInputStream.Close();
                     return ex.Message;
                 }
             }
             objZipEntry = objZipInputStream.GetNextEntry();
         }
         sortedFolders.Sort();
         foreach (string s in sortedFolders)
         {
             try
             {
                 AddFolder(settings, DestFolder, s.ToString(), storageLocation);
             }
             catch (Exception ex)
             {
                 return ex.Message;
             }
         }
         objZipInputStream = new ZipInputStream(GetFileStream(file));
         objZipEntry = objZipInputStream.GetNextEntry();
         while (objZipEntry != null)
         {
             if (!objZipEntry.IsDirectory)
             {
                 if (objPortalController.HasSpaceAvailable(FolderPortalId, objZipEntry.Size))
                 {
                     strFileName = Path.GetFileName(objZipEntry.Name);
                     if (!String.IsNullOrEmpty(strFileName))
                     {
                         strExtension = Path.GetExtension(strFileName).Replace(".", "");
                         if (("," + Host.FileExtensions.ToLower()).IndexOf("," + strExtension.ToLower()) != 0 || isHost)
                         {
                             try
                             {
                                 string folderPath = System.IO.Path.GetDirectoryName(DestFolder + objZipEntry.Name.Replace("/", "\\"));
                                 DirectoryInfo Dinfo = new DirectoryInfo(folderPath);
                                 if (!Dinfo.Exists)
                                 {
                                     AddFolder(settings, DestFolder, objZipEntry.Name.Substring(0, objZipEntry.Name.Replace("/", "\\").LastIndexOf("\\")));
                                 }
                                 string zipEntryFileName = DestFolder + objZipEntry.Name.Replace("/", "\\");
                                 strMessage += AddFile(FolderPortalId, objZipInputStream, zipEntryFileName, "", objZipEntry.Size, Globals.GetSubFolderPath(zipEntryFileName, settings.PortalId), false, false);
                             }
                             catch (Exception ex)
                             {
                                 if (objZipInputStream != null)
                                 {
                                     objZipInputStream.Close();
                                 }
                                 return ex.Message;
                             }
                         }
                         else
                         {
                             strMessage += "<br>" + string.Format(Localization.GetString("RestrictedFileType"), strFileName, Host.FileExtensions.Replace(",", ", *."));
                         }
                     }
                 }
                 else
                 {
                     strMessage += "<br>" + string.Format(Localization.GetString("DiskSpaceExceeded"), strFileName);
                 }
             }
             objZipEntry = objZipInputStream.GetNextEntry();
         }
     }
     finally
     {
         if (objZipInputStream != null)
         {
             objZipInputStream.Close();
             objZipInputStream.Dispose();
         }
     }
     return strMessage;
 }
Beispiel #20
0
 public static void UnZip(string FileToUpZip, string ZipedFolder)
 {
     if (File.Exists(FileToUpZip))
     {
         if (!Directory.Exists(ZipedFolder))
         {
             Directory.CreateDirectory(ZipedFolder);
         }
         ZipInputStream stream = new ZipInputStream(File.OpenRead(FileToUpZip));
         try
         {
             ZipEntry entry;
             while ((entry = stream.GetNextEntry()) != null)
             {
                 if (entry.Name != string.Empty)
                 {
                     string path = Path.Combine(ZipedFolder, entry.Name);
                     if (path.EndsWith("/") || path.EndsWith(@"\"))
                     {
                         Directory.CreateDirectory(path);
                         continue;
                     }
                     string directoryName = Path.GetDirectoryName(path);
                     if (!Directory.Exists(directoryName))
                     {
                         Directory.CreateDirectory(directoryName);
                     }
                     FileStream stream2 = File.Create(path);
                     try
                     {
                         bool flag;
                         int count = 0x800;
                         byte[] buffer = new byte[0x800];
                         goto Label_00FC;
                     Label_00D0:
                         count = stream.Read(buffer, 0, buffer.Length);
                         if (count <= 0)
                         {
                             continue;
                         }
                         stream2.Write(buffer, 0, count);
                     Label_00FC:
                         flag = true;
                         goto Label_00D0;
                     }
                     finally
                     {
                         stream2.Close();
                         stream2.Dispose();
                         stream2 = null;
                     }
                 }
             }
         }
         finally
         {
             stream.Close();
             stream.Dispose();
             stream = null;
         }
     }
 }
Beispiel #21
0
		private static bool InitializeIcuData()
		{
			var icuDir = Icu.DefaultDirectory;
			ZipInputStream zipIn = null;
			try
			{
				try
				{
					var baseDir = FwDirectoryFinder.DataDirectory;
					zipIn = new ZipInputStream(File.OpenRead(Path.Combine(baseDir, "Icu50.zip")));
				}
				catch (Exception e1)
				{
					MessageBoxUtils.Show("Something is wrong with the file you chose." + Environment.NewLine +
						" The file could not be opened. " + Environment.NewLine + Environment.NewLine +
						"   The error message was: '" + e1.Message);
				}
				if (zipIn == null)
					return false;
				Icu.Cleanup();
				foreach (var dir in Directory.GetDirectories(icuDir))
				{
					var subdir = Path.GetFileName(dir).ToLowerInvariant();
					if (subdir =="data" ||
						(subdir.StartsWith("icudt") && subdir.EndsWith("l")))
					{
						Directory.Delete(dir, true);
					}
				}
				ZipEntry entry;
				while ((entry = zipIn.GetNextEntry()) != null)
				{
					var dirName = Path.GetDirectoryName(entry.Name);
					var match = new Regex(@"^ICU\d\d[\\/]?(.*)$").Match(dirName);
					if (match.Success) // Zip file was built in a way that includes the root directory name.
						dirName = match.Groups[1].Value; // Strip it off. May leave empty string.
					var fileName = Path.GetFileName(entry.Name);
					var fOk = UnzipFile(zipIn, fileName, entry.Size, Path.Combine(icuDir, dirName));
					if (!fOk)
						return false;
				}
				return true;
			}
			finally
			{
				if (zipIn != null)
					zipIn.Dispose();
			}
		}