public static void ExtractZipFile(string archiveFilenameIn, string password, string outFolder) { ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { FileStream fs = File.OpenRead (archiveFilenameIn); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile (fs); if (!String.IsNullOrEmpty (password)) { zf.Password = password; // AES encrypted entries are handled automatically } foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } String entryFileName = zipEntry.Name; // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream (zipEntry); // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine (outFolder, entryFileName); string directoryName = Path.GetDirectoryName (fullZipToPath); if (directoryName.Length > 0) Directory.CreateDirectory (directoryName); // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create (fullZipToPath)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy (zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close (); // Ensure we release resources } } }
} // End UnZip /// <summary> /// Unzip a local file and return its contents via streamreader to a local the same location as the ZIP. /// </summary> /// <param name="zipFile">Location of the zip on the HD</param> /// <returns>List of unzipped file names</returns> public static List <string> UnzipToFolder(string zipFile) { //1. Initialize: var files = new List <string>(); var slash = zipFile.LastIndexOf(Path.DirectorySeparatorChar); var outFolder = ""; if (slash > 0) { outFolder = zipFile.Substring(0, slash); } ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { var fs = File.OpenRead(zipFile); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); foreach (ZipEntry zipEntry in zf) { //Ignore Directories if (!zipEntry.IsFile) { continue; } //Remove the folder from the entry var entryFileName = Path.GetFileName(zipEntry.Name); if (entryFileName == null) { continue; } var buffer = new byte[4096]; // 4K is optimum var zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. var fullZipToPath = Path.Combine(outFolder, entryFileName); //Save the file name for later: files.Add(fullZipToPath); //Log.Trace("Data.UnzipToFolder(): Input File: " + zipFile + ", Output Directory: " + fullZipToPath); //Copy the data in buffer chunks using (var streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } return(files); } // End UnZip
public void Release() { if (zip != null) { zip.Close(); zip = null; } isValid = false; }
protected void ButtonSenadores_Click(object sender, EventArgs e) { String atualDir = Server.MapPath("Upload"); if (FileUpload.FileName != "") { FileUpload.SaveAs(atualDir + "//" + FileUpload.FileName); ICSharpCode.SharpZipLib.Zip.ZipFile file = null; try { file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "//" + FileUpload.FileName); if (file.TestArchive(true) == false) { Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>"); return; } } finally { if (file != null) { file.Close(); } } ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null); File.Delete(atualDir + "//" + FileUpload.FileName); CarregarSenadores(atualDir); } else { DirectoryInfo dir = new DirectoryInfo(atualDir); foreach (FileInfo file in dir.GetFiles("*.zip")) { ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(file.FullName, file.DirectoryName, null); File.Delete(file.FullName); CarregarSenadores(file.DirectoryName); } } Cache.Remove("menorAnoSenadores"); Cache.Remove("ultimaAtualizacaoSenadores"); Cache.Remove("tableSenadores"); Cache.Remove("tableDespesaSenadores"); Cache.Remove("tablePartidoSenadores"); }
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Tag == null) { return; } if (e.Node.Tag.ToString() == "FILE" || e.Node.Tag.ToString() == "ZIP") { LearnLifeCore.FileReader.FileReader fileReader = new LearnLifeCore.FileReader.FileReader(); fileReader.Border = LearnLifeWin.Properties.Settings.Default.ReadFileBorder; string filename = e.Node.Name; if (e.Node.Tag.ToString() == "ZIP" && e.Node.Parent.Parent.Tag.ToString() == "ZIPROOT") { OpenFile = string.Empty; filename = Path.Combine(Path.GetTempPath(), e.Node.Text); ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { FileStream fs = File.OpenRead(e.Node.Parent.Parent.Name); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); byte[] buffer = new byte[4096]; Stream zipStream = zf.GetInputStream(zf.GetEntry(e.Node.Name)); using (FileStream streamWriter = File.Create(filename)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zipStream, streamWriter, buffer); } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } } else { isModified = false; OpenFile = filename; } ReadLifeFile(fileReader, filename); if (e.Node.Tag.ToString() == "ZIP" && e.Node.Parent.Parent.Tag.ToString() == "ZIPROOT") { File.Delete(filename); } } }
internal static void ZipTempMapFiles(string strDestMapNameAndPath) { ICSharpCode.SharpZipLib.Zip.ZipFile NewMapZipped = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(strDestMapNameAndPath); NewMapZipped.BeginUpdate(); ZipFilesInDir(new DirectoryInfo(MAPS_INITIAL_DIR), NewMapZipped); //NewMapZipped.Add(@"Maps\Multiplayer\"+"\\"+); //NewMapZipped.Add(@"Maps\Multiplayer\TestMap\GroundTerrain.bin"); NewMapZipped.CommitUpdate(); NewMapZipped.Close(); }
public static void ExtractZipFile(string archiveFilenameIn, string password, string outFolder) { ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { FileStream fs = File.OpenRead(archiveFilenameIn); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); if (!String.IsNullOrEmpty(password)) { zf.Password = password; // AES encrypted entries are handled automatically } foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } String entryFileName = zipEntry.Name; // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine(outFolder, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create(fullZipToPath)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } }
private static string ExtractZip(FileInfo info) { var extractDir = Path.Combine(info.Directory.FullName, info.Name.Substring(0, info.Name.Length - info.Extension.Length)); if (!Directory.Exists(extractDir)) { Directory.CreateDirectory(extractDir); } var zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(info.FullName); foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zip) { var dst = Path.Combine(extractDir, entry.Name.Replace('/', Path.DirectorySeparatorChar)); if (File.Exists(dst)) { File.Delete(dst); } var inf = new FileInfo(dst); if (!inf.Directory.Exists) { inf.Directory.Create(); } using (var zipStream = zip.GetInputStream(entry)) { using (var output = File.OpenWrite(dst)) { var buffer = new byte[4096]; while (zipStream.Position < entry.Size) { var read = zipStream.Read(buffer, 0, buffer.Length); if (read > 0) { output.Write(buffer, 0, read); } else { break; } } } } } zip.Close(); return(extractDir); }
public static bool DeleteEntry(string zipFileName, string entryname, string password = null) { try { SharpZipLib.Zip.ZipFile s = new SharpZipLib.Zip.ZipFile(zipFileName); s.Password = password; SharpZipLib.Zip.ZipEntry entry = s.GetEntry(entryname); if (null == entry) { s.Close(); return(true); } s.BeginUpdate(); s.Delete(entry); s.CommitUpdate(); s.Close(); return(true); } catch (Exception e) { LogUtil.LogError(e.Message); return(false); } }
private void ExtractXmlFiles(Stream stream) { #if SILVERLIGHT StreamResourceInfo zipStream = new StreamResourceInfo(stream, null); #else ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(stream); #endif foreach (string file in FilesToDownload) { UpdateProgress(0, "Decompressing " + file + "..."); #if !SILVERLIGHT // we don't actually want ClientBin part in the zip string part = file.Remove(0, 10); StreamReader sr = new StreamReader(zipFile.GetInputStream(zipFile.GetEntry(part))); string unzippedFile = sr.ReadToEnd(); StreamWriter writer = new StreamWriter(file); writer.Write(unzippedFile); writer.Close(); #else Uri part = new Uri(file, UriKind.Relative); // This reading method only works in Silverlight due to the GetResourceStream not existing with 2 arguments in // regular .Net-land StreamResourceInfo fileStream = Application.GetResourceStream(zipStream, part); StreamReader sr = new StreamReader(fileStream.Stream); string unzippedFile = sr.ReadToEnd(); //Write it in a special way when using IsolatedStorage, due to IsolatedStorage //having a huge performance issue when writing small chunks IsolatedStorageFileStream isfs = GetFileStream(file, true); char[] charBuffer = unzippedFile.ToCharArray(); int fileSize = charBuffer.Length; byte[] byteBuffer = new byte[fileSize]; for (int i = 0; i < fileSize; i++) { byteBuffer[i] = (byte)charBuffer[i]; } isfs.Write(byteBuffer, 0, fileSize); isfs.Close(); #endif UpdateProgress(0, "Finished " + file + "..."); } #if !SILVERLIGHT zipFile.Close(); #endif }
public static bool UpdateEntry(string zipFileName, string entryname, string filename, string password = null) { try { SharpZipLib.Zip.ZipFile s = new SharpZipLib.Zip.ZipFile(zipFileName); s.Password = password; SharpZipLib.Zip.StaticDiskDataSource data = new SharpZipLib.Zip.StaticDiskDataSource(filename); s.BeginUpdate(); s.Add(data, entryname); s.CommitUpdate(); s.Close(); return(true); } catch (Exception e) { LogUtil.LogError(e.Message); return(false); } }
public static void UnCompressZipFile(System.IO.Stream source) { ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(source); try { foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zipFile) { if (!entry.IsFile) { continue; } if (entry.IsCrypted) { throw new Exception(string.Format("UnCompressZipFile. {0} ", "Compress file encrypted.")); } string filetobecreate = System.IO.Path.Combine(Util.ExecutableDirectory(), entry.Name); using (System.IO.Stream data = zipFile.GetInputStream(entry)) { using (System.IO.Stream write = System.IO.File.Open(filetobecreate, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { try { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(data, write, buffer); } finally { write.Close(); data.Close(); } } } } } finally { zipFile.IsStreamOwner = true; zipFile.Close(); } }
public bool CreateLegacyGoPackage(string sourceArchive, string sourceDirectory) { try { var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(sourceArchive); zipFile.BeginUpdate(); foreach (var file in Directory.EnumerateFiles( sourceDirectory, "*.*", searchOption: SearchOption.TopDirectoryOnly)) { var fileInfo = new FileInfo(file); Log.Info($"Adding File: {fileInfo.Name} to Package"); zipFile.Add(fileInfo.FullName, fileInfo.Name); Log.Info($"Successfully Added File: {fileInfo.Name} to Package"); } Log.Info("Updating Package entries this may take time dependent on package size."); zipFile.CommitUpdate(); zipFile.Close(); Log.Info("Packaging Successfully completed."); return(true); } catch (Exception createGoEx) { Log.Error($"Failed to Packaging Legacy Go deliverable: {sourceArchive} - {createGoEx.Message}"); if (createGoEx.InnerException != null) { Log.Error($"Inner Exception: {createGoEx.InnerException.Message}"); } return(false); } }
private void InitTreeSub(TreeNode parent, string directory) { foreach (string dir in Directory.EnumerateDirectories(directory, "*", SearchOption.TopDirectoryOnly)) { TreeNode dirNode = parent.Nodes.Add(dir, Path.GetFileName(dir), 0); dirNode.Tag = "DIR"; InitTreeSub(dirNode, dir); } foreach (string file in Directory.EnumerateFiles(directory, "*.*", SearchOption.TopDirectoryOnly)) { if (file.EndsWith(".zip")) { TreeNode zipNode = parent.Nodes.Add(file, Path.GetFileName(file), 3); zipNode.Tag = "ZIPROOT"; // http://wiki.sharpdevelop.net/SharpZipLib-Zip-Samples.ashx ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { FileStream fs = File.OpenRead(file); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); zf = InitTreeZip(zipNode, file, zf); } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } continue; } TreeNode fileNode = parent.Nodes.Add(file, Path.GetFileName(file), 1); fileNode.Tag = "FILE"; } }
public static byte[] ReadZipBytes(string pathRoot, string relativeFileName) { //获取压缩文件内容 byte[] data = null; ICSharpCode.SharpZipLib.Zip.ZipFile zfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(pathRoot); try { ICSharpCode.SharpZipLib.Zip.ZipEntry entry = zfile.GetEntry(relativeFileName);//"assets/Builds/Indep_Role_FabRole01.assetbundle"); if (entry == null) { return(data); } Stream sm = zfile.GetInputStream(entry.ZipFileIndex); data = new byte[entry.Size]; sm.Read(data, 0, data.Length); sm.Close(); } catch (Exception e) { Debug.LogError(e.ToString()); } finally { zfile.Close(); } return(data); }
/// <summary> /// 根据压缩包路径读取此压缩包内文件个数 /// </summary> /// <param name="zipFilePath"></param> /// <returns></returns> public static int CountZipFile(string zipFilePath) { ZipFile zipFile = null; try { using (zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipFilePath)) { long l_New = zipFile.Count; return(Convert.ToInt32(l_New)); } } catch { return(0); } finally { if (zipFile != null) { zipFile.Close(); } } }
private void deploybtn_click(object sender, EventArgs e) { save(); string filedata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<Deployment xmlns=\"http://schemas.microsoft.com/windowsphone/2009/deployment\" AppPlatformVersion=\"7.1\">" + " <App xmlns=\"\" ProductID=\"{" + Guid.NewGuid().ToString() + "}\" Title=\"" + curMenu.name + "\" RuntimeType=\"Silverlight\" Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"Jaxbot\" Description=\"Folder\" Publisher=\"WindowsPhoneHacker\">" + " <IconPath IsRelative=\"true\" IsResource=\"false\">ApplicationIcon.png</IconPath>" + " <Capabilities>" + " <Capability Name=\"ID_CAP_GAMERSERVICES\"/>" + " <Capability Name=\"ID_CAP_IDENTITY_DEVICE\"/>" + " <Capability Name=\"ID_CAP_IDENTITY_USER\"/>" + " <Capability Name=\"ID_CAP_LOCATION\"/>" + " <Capability Name=\"ID_CAP_MEDIALIB\"/>" + " <Capability Name=\"ID_CAP_MICROPHONE\"/>" + " <Capability Name=\"ID_CAP_NETWORKING\"/>" + " <Capability Name=\"ID_CAP_PHONEDIALER\"/>" + " <Capability Name=\"ID_CAP_PUSH_NOTIFICATION\"/>" + " <Capability Name=\"ID_CAP_SENSORS\"/>" + " <Capability Name=\"ID_CAP_WEBBROWSERCOMPONENT\"/>" + " <Capability Name=\"ID_CAP_ISV_CAMERA\"/>" + " <Capability Name=\"ID_CAP_CONTACTS\"/>" + " <Capability Name=\"ID_CAP_APPOINTMENTS\"/>" + " </Capabilities>" + " <Tasks>" + " <DefaultTask Name =\"_default\" NavigationPage=\"MainPage.xaml\"/>" + " </Tasks>" + " <Tokens>" + " <PrimaryToken TokenID=\"IndependentFolderToken\" TaskName=\"_default\">" + " <TemplateType5>" + " <BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">Background.png</BackgroundImageURI>" + " <Count>0</Count>" + " <Title>Folder</Title>" + " </TemplateType5>" + " </PrimaryToken>" + " </Tokens>" + " </App>" + "</Deployment>"; MemoryStream original = new MemoryStream(); var res = Application.GetResourceStream(new Uri("IndependentFolder.xap", UriKind.Relative)).Stream; res.CopyTo(original); ICSharpCode.SharpZipLib.Zip.ZipFile file = new ICSharpCode.SharpZipLib.Zip.ZipFile(original); file.BeginUpdate(); MemoryStream filestr = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(filedata)); CustomStaticDataSource sds = new CustomStaticDataSource(); sds.SetStream(filestr); file.Add(sds, "WMAppManifest.xml"); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { foreach (appentry app in curMenu.apps) { var imgfile = store.OpenFile(app.guid + ".jpg", FileMode.Open, FileAccess.Read); CustomStaticDataSource sdsimg = new CustomStaticDataSource(); imgfile.CopyTo(sdsimg._stream); imgfile.Close(); sdsimg._stream.Position = 0; //sdsimg.SetStream(imgfile); file.Add(sdsimg, "apps/" + app.guid + ".jpg"); file.CommitUpdate(); file.BeginUpdate(); } var menufile = store.OpenFile(curMenu.name + ".folder", FileMode.Open, FileAccess.Read); CustomStaticDataSource sdsmenu = new CustomStaticDataSource(); sdsmenu.SetStream(menufile); file.Add(sdsmenu, "menu.folder"); file.CommitUpdate(); file.IsStreamOwner = false; file.Close(); original.Position = 0; using (var stream = new IsolatedStorageFileStream("package." + curMenu.name + ".zip", FileMode.Create, store)) { original.CopyTo(stream); } } /* * ICSharpCode.SharpZipLib.Zip.ZipOutputStream str = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(new MemoryStream()); * str.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("WMAppManifest.xml")); */ //ICSharpCode.SharpZipLib.Zip.zipout //file.Add(str); XapHandler.XapDeployerInterop.Initialize(); XapHandler.XapDeployerInterop.ReadyIsAppInstalled(@"\Applications\Data\5b594f78-a744-4f8a-85d2-f0f55f411832\Data\IsolatedStore\package." + curMenu.name + ".zip"); XapHandler.XapDeployerInterop.FinishInstall(false); }
private void btnExport_Click(object sender, EventArgs e) { //acquire target var sfd = new SaveFileDialog(); sfd.Filter = "XRNS (*.xrns)|*.xrns"; if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } //configuration: var outPath = sfd.FileName; string templatePath = Path.Combine(Path.GetDirectoryName(outPath), "template.xrns"); int configuredPatternLength = int.Parse(txtPatternLength.Text); //load template MemoryStream msSongXml = new MemoryStream(); var zfTemplate = new ICSharpCode.SharpZipLib.Zip.ZipFile(templatePath); { int zfSongXmlIndex = zfTemplate.FindEntry("Song.xml", true); using (var zis = zfTemplate.GetInputStream(zfTemplate.GetEntry("Song.xml"))) { byte[] buffer = new byte[4096]; // 4K is optimum ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zis, msSongXml, buffer); } } XElement templateRoot = XElement.Parse(System.Text.Encoding.UTF8.GetString(msSongXml.ToArray())); //get the pattern pool, and whack the child nodes var xPatterns = templateRoot.XPathSelectElement("//Patterns"); var xPatternPool = xPatterns.Parent; xPatterns.Remove(); var writer = new StringWriter(); writer.WriteLine("<Patterns>"); int pulse0_lastNote = -1; int pulse0_lastType = -1; int pulse1_lastNote = -1; int pulse1_lastType = -1; int tri_lastNote = -1; int noise_lastNote = -1; int patternCount = 0; int time = 0; while (time < Log.Count) { patternCount++; //begin writing pattern: open the tracks list writer.WriteLine("<Pattern>"); writer.WriteLine("<NumberOfLines>{0}</NumberOfLines>", configuredPatternLength); writer.WriteLine("<Tracks>"); //write the pulse tracks for (int TRACK = 0; TRACK < 2; TRACK++) { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); int lastNote = TRACK == 0 ? pulse0_lastNote : pulse1_lastNote; int lastType = TRACK == 0 ? pulse0_lastType : pulse1_lastType; for (int i = 0; i < configuredPatternLength; i++) { int patLine = i; int index = i + time; if (index >= Log.Count) { continue; } var rec = Log[index]; PulseState pulse = new PulseState(); if (TRACK == 0) { pulse = rec.pulse0; } if (TRACK == 1) { pulse = rec.pulse1; } //transform quieted notes to dead notes //blech its buggy, im tired //if (pulse.vol == 0) // pulse.en = false; bool keyoff = false, keyon = false; if (lastNote != -1 && !pulse.en) { lastNote = -1; lastType = -1; keyoff = true; } else if (lastNote != pulse.note && pulse.en) { keyon = true; } if (lastType != pulse.type && pulse.note != -1) { keyon = true; } if (pulse.en) { lastNote = pulse.note; lastType = pulse.type; } writer.WriteLine("<Line index=\"{0}\">", patLine); writer.WriteLine("<NoteColumns>"); writer.WriteLine("<NoteColumn>"); if (keyon) { writer.WriteLine("<Note>{0}</Note>", NameForNote(pulse.note)); writer.WriteLine("<Instrument>{0:X2}</Instrument>", pulse.type); } else if (keyoff) { writer.WriteLine("<Note>OFF</Note>"); } if (lastNote != -1) { writer.WriteLine("<Volume>{0:X2}</Volume>", pulse.vol * 8); } writer.WriteLine("</NoteColumn>"); writer.WriteLine("</NoteColumns>"); writer.WriteLine("</Line>"); } //close PatternTrack writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); if (TRACK == 0) { pulse0_lastNote = lastNote; pulse0_lastType = lastType; } else { pulse1_lastNote = lastNote; pulse1_lastType = lastType; } } //pulse tracks loop //triangle track generation { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); for (int i = 0; i < configuredPatternLength; i++) { int patLine = i; int index = i + time; if (index >= Log.Count) { continue; } var rec = Log[index]; TriangleState tri = rec.triangle; { bool keyoff = false, keyon = false; if (tri_lastNote != -1 && !tri.en) { tri_lastNote = -1; keyoff = true; } else if (tri_lastNote != tri.note && tri.en) { keyon = true; } if (tri.en) { tri_lastNote = tri.note; } writer.WriteLine("<Line index=\"{0}\">", patLine); writer.WriteLine("<NoteColumns>"); writer.WriteLine("<NoteColumn>"); if (keyon) { writer.WriteLine("<Note>{0}</Note>", NameForNote(tri.note)); writer.WriteLine("<Instrument>08</Instrument>"); } else if (keyoff) { writer.WriteLine("<Note>OFF</Note>"); } //no need for tons of these //if(keyon) writer.WriteLine("<Volume>80</Volume>"); writer.WriteLine("</NoteColumn>"); writer.WriteLine("</NoteColumns>"); writer.WriteLine("</Line>"); } } //close PatternTrack writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); } //noise track generation { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); for (int i = 0; i < configuredPatternLength; i++) { int patLine = i; int index = i + time; if (index >= Log.Count) { continue; } var rec = Log[index]; NoiseState noise = rec.noise; //transform quieted notes to dead notes //blech its buggy, im tired //if (noise.vol == 0) // noise.en = false; { bool keyoff = false, keyon = false; if (noise_lastNote != -1 && !noise.en) { noise_lastNote = -1; keyoff = true; } else if (noise_lastNote != noise.note && noise.en) { keyon = true; } if (noise.en) { noise_lastNote = noise.note; } writer.WriteLine("<Line index=\"{0}\">", patLine); writer.WriteLine("<NoteColumns>"); writer.WriteLine("<NoteColumn>"); if (keyon) { writer.WriteLine("<Note>{0}</Note>", NameForNote(noise.note)); writer.WriteLine("<Instrument>04</Instrument>"); } else if (keyoff) { writer.WriteLine("<Note>OFF</Note>"); } if (noise_lastNote != -1) { writer.WriteLine("<Volume>{0:X2}</Volume>", noise.vol * 8); } writer.WriteLine("</NoteColumn>"); writer.WriteLine("</NoteColumns>"); writer.WriteLine("</Line>"); } } //close PatternTrack writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); } //noise track generation //write empty track for now for pcm for (int TRACK = 4; TRACK < 5; TRACK++) { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); } //we definitely need a dummy master track now writer.WriteLine("<PatternMasterTrack type=\"PatternMasterTrack\">"); writer.WriteLine("</PatternMasterTrack>"); //close tracks writer.WriteLine("</Tracks>"); //close pattern writer.WriteLine("</Pattern>"); time += configuredPatternLength; } //main pattern loop writer.WriteLine("</Patterns>"); writer.Flush(); var xNewPatternList = XElement.Parse(writer.ToString()); xPatternPool.Add(xNewPatternList); //write pattern sequence writer = new StringWriter(); writer.WriteLine("<SequenceEntries>"); for (int i = 0; i < patternCount; i++) { writer.WriteLine("<SequenceEntry>"); writer.WriteLine("<IsSectionStart>false</IsSectionStart>"); writer.WriteLine("<Pattern>{0}</Pattern>", i); writer.WriteLine("</SequenceEntry>"); } writer.WriteLine("</SequenceEntries>"); var xPatternSequence = templateRoot.XPathSelectElement("//PatternSequence"); xPatternSequence.XPathSelectElement("SequenceEntries").Remove(); xPatternSequence.Add(XElement.Parse(writer.ToString())); //copy template file to target File.Delete(outPath); File.Copy(templatePath, outPath); var msOutXml = new MemoryStream(); templateRoot.Save(msOutXml); msOutXml.Flush(); msOutXml.Position = 0; var zfOutput = new ICSharpCode.SharpZipLib.Zip.ZipFile(outPath); zfOutput.BeginUpdate(); zfOutput.Add(new Stupid { stream = msOutXml }, "Song.xml"); zfOutput.CommitUpdate(); zfOutput.Close(); //for easier debugging, write patterndata XML //DUMP_TO_DISK(msOutXml.ToArray()) }
private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e) { // Zip up the iso store MemoryStream original = new MemoryStream(); ICSharpCode.SharpZipLib.Zip.ZipFile file = new ICSharpCode.SharpZipLib.Zip.ZipFile(original); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { foreach (string fname in store.GetFileNames()) { file.BeginUpdate(); CustomStaticDataSource sdsf = new CustomStaticDataSource(); var storefile = store.OpenFile(fname, FileMode.Open, FileAccess.Read); storefile.CopyTo(sdsf._stream); storefile.Close(); sdsf._stream.Position = 0; file.Add(sdsf, fname); file.CommitUpdate(); } file.IsStreamOwner = false; file.Close(); original.Position = 0; // Connect to live API LiveAuthClient auth = new LiveAuthClient("00000000440E7119"); auth.InitializeAsync(); auth.InitializeCompleted += (e1, e2) => { // Show login dialog auth.LoginAsync(new string[] { "wl.skydrive_update" }); auth.LoginCompleted += (e3, e4) => { if (e4.Status == LiveConnectSessionStatus.Connected) { LiveConnectClient client = new LiveConnectClient(e4.Session); // Upload that zip we just made client.UploadAsync("me/skydrive/", "wphfolders.zip", original, OverwriteOption.Overwrite); client.UploadCompleted += (ucSender, ucEvent) => { MessageBox.Show("Uploaded wphfolders.zip to the root of your SkyDrive. Feel free to move it, but put it back if you need to restore!"); }; } else { MessageBox.Show("Not connected to SkyDrive"); } }; }; } }
public void Save(string FileName, bool OverWrite) { if (System.IO.File.Exists(FileName) && OverWrite == false) { return; } if (System.IO.File.Exists(FileName)) { System.IO.File.Delete(FileName); } #region Generate The XML File StringBuilder _Builder = new StringBuilder("<gg2world "); _Builder.Append("worldname=\""); _Builder.Append(WorldName); _Builder.Append("\" minpoint=\""); _Builder.Append(GetMin().ToString()); _Builder.Append("\" maxpoint=\""); _Builder.Append(GetMax().ToString()); _Builder.Append("\" >\r\n"); // Append Screen Info foreach (var S in Screens.Values) { _Builder.Append("\t" + S.ExportToXML()); } _Builder.Append("</gg2world>\r\n"); #endregion // Get the Static Variables for the Save Operations string _BaseDirectory = FileName.Substring(0, FileName.LastIndexOf("\\")); Guid _TmpDirGuid = Guid.NewGuid(); string _TmpDir = _TmpDirGuid.ToString().Substring(0, 10); // Create Directory If Needed if (!System.IO.Directory.Exists(_BaseDirectory)) { System.IO.Directory.CreateDirectory(_BaseDirectory); } // Write the XML File System.IO.File.AppendAllText(FileName, _Builder.ToString()); // Create the TempDirectories System.IO.Directory.CreateDirectory(_BaseDirectory + "\\" + _TmpDir + "_Back" + "\\"); System.IO.Directory.CreateDirectory(_BaseDirectory + "\\" + _TmpDir + "_Pass" + "\\"); System.IO.Directory.CreateDirectory(_BaseDirectory + "\\" + _TmpDir + "_Objects" + "\\"); // Save All Images in Zip File to Temp Directory foreach (var S in Screens.Keys) { var _Screen = Screens[S]; //_Screen.BackgroundImage.Save(_BaseDirectory + "\\" + _TmpDir + "_Back" + "\\" + S + "_Back.png"); //_Screen.PassableLayer.Save(_BaseDirectory + "\\" + _TmpDir + "_Pass" + "\\" + S + "_Pass.png"); //GG2DLib.ResourceManager.ImageMethods.SaveImageAsJpg(_Screen.BackgroundImage, _BaseDirectory + "\\" + _TmpDir + "_Back" + "\\" + S + "_Back.png", 95L); //GG2DLib.ResourceManager.ImageMethods.SaveImageAsJpg(_Screen.PassableLayer, _BaseDirectory + "\\" + _TmpDir + "_Pass" + "\\" + S + "_Pass.png", 95L); // _Screen.BackgroundImage.Save(_BaseDirectory + "\\" + _TmpDir + "_Back" + "\\" + S + "_Back.jpg", jgpEncoder, _Params); //_Screen.PassableLayer.Save(_BaseDirectory + "\\" + _TmpDir + "_Pass" + "\\" + S + "_Pass.jpg", jgpEncoder, _Params); } // Save All The Objects foreach (string _K in ResourceManager.GetMapObjectKeys()) { var _TmpImg = ResourceManager.GetMapObjectImageStart(_K); _TmpImg.Save(_BaseDirectory + "\\" + _TmpDir + "_Objects" + "\\" + _K.Substring(_K.LastIndexOf("\\") + 1) + "_Object.png", System.Drawing.Imaging.ImageFormat.Png); ResourceManager.GetMapObjectImageEnd(_K); } // Create The Zip File for the Images if (System.IO.File.Exists(_BaseDirectory + "\\" + WorldName + "_Data.zip")) { System.IO.File.Delete(_BaseDirectory + "\\" + WorldName + "_Data.zip"); } ICSharpCode.SharpZipLib.Zip.ZipFile _Z = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(_BaseDirectory + "\\" + WorldName + "_Data.zip"); // Add The Backgrounds To The Zip File _Z.BeginUpdate(); foreach (string _F in System.IO.Directory.GetFiles(_BaseDirectory + "\\" + _TmpDir + "_Back" + "\\")) { _Z.Add(_F, "Back\\" + _F.Substring(_F.LastIndexOf("\\") + 1)); } _Z.CommitUpdate(); // Add The Passable To The Zip File _Z.BeginUpdate(); foreach (string _F in System.IO.Directory.GetFiles(_BaseDirectory + "\\" + _TmpDir + "_Pass" + "\\")) { _Z.Add(_F, "Pass\\" + _F.Substring(_F.LastIndexOf("\\") + 1)); } _Z.CommitUpdate(); // Add The Objects To The Zip File _Z.BeginUpdate(); foreach (string _F in System.IO.Directory.GetFiles(_BaseDirectory + "\\" + _TmpDir + "_Objects" + "\\")) { _Z.Add(_F, "Objects\\" + _F.Substring(_F.LastIndexOf("\\") + 1)); } _Z.CommitUpdate(); _Z.Close(); // Cleanup Temp Directories System.IO.Directory.Delete(_BaseDirectory + "\\" + _TmpDir + "_Back" + "\\", true); System.IO.Directory.Delete(_BaseDirectory + "\\" + _TmpDir + "_Pass" + "\\", true); System.IO.Directory.Delete(_BaseDirectory + "\\" + _TmpDir + "_Objects" + "\\", true); return; }
private void btnExport_Click(object sender, EventArgs e) { //acquire target var sfd = new SaveFileDialog(); sfd.Filter = "XRNS (*.xrns)|*.xrns"; if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; //configuration: var outPath = sfd.FileName; string templatePath = Path.Combine(Path.GetDirectoryName(outPath), "template.xrns"); int configuredPatternLength = int.Parse(txtPatternLength.Text); //load template MemoryStream msSongXml = new MemoryStream(); var zfTemplate = new ICSharpCode.SharpZipLib.Zip.ZipFile(templatePath); { int zfSongXmlIndex = zfTemplate.FindEntry("Song.xml", true); using (var zis = zfTemplate.GetInputStream(zfTemplate.GetEntry("Song.xml"))) { byte[] buffer = new byte[4096]; // 4K is optimum ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zis, msSongXml, buffer); } } XElement templateRoot = XElement.Parse(System.Text.Encoding.UTF8.GetString(msSongXml.ToArray())); //get the pattern pool, and whack the child nodes var xPatterns = templateRoot.XPathSelectElement("//Patterns"); var xPatternPool = xPatterns.Parent; xPatterns.Remove(); var writer = new StringWriter(); writer.WriteLine("<Patterns>"); int pulse0_lastNote = -1; int pulse0_lastType = -1; int pulse1_lastNote = -1; int pulse1_lastType = -1; int tri_lastNote = -1; int noise_lastNote = -1; int patternCount = 0; int time = 0; while (time < Log.Count) { patternCount++; //begin writing pattern: open the tracks list writer.WriteLine("<Pattern>"); writer.WriteLine("<NumberOfLines>{0}</NumberOfLines>", configuredPatternLength); writer.WriteLine("<Tracks>"); //write the pulse tracks for (int TRACK = 0; TRACK < 2; TRACK++) { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); int lastNote = TRACK == 0 ? pulse0_lastNote : pulse1_lastNote; int lastType = TRACK == 0 ? pulse0_lastType : pulse1_lastType; for (int i = 0; i < configuredPatternLength; i++) { int patLine = i; int index = i + time; if (index >= Log.Count) continue; var rec = Log[index]; PulseState pulse = new PulseState(); if (TRACK == 0) pulse = rec.pulse0; if (TRACK == 1) pulse = rec.pulse1; //transform quieted notes to dead notes //blech its buggy, im tired //if (pulse.vol == 0) // pulse.en = false; bool keyoff = false, keyon = false; if (lastNote != -1 && !pulse.en) { lastNote = -1; lastType = -1; keyoff = true; } else if (lastNote != pulse.note && pulse.en) keyon = true; if (lastType != pulse.type && pulse.note != -1) keyon = true; if (pulse.en) { lastNote = pulse.note; lastType = pulse.type; } writer.WriteLine("<Line index=\"{0}\">", patLine); writer.WriteLine("<NoteColumns>"); writer.WriteLine("<NoteColumn>"); if (keyon) { writer.WriteLine("<Note>{0}</Note>", NameForNote(pulse.note)); writer.WriteLine("<Instrument>{0:X2}</Instrument>", pulse.type); } else if (keyoff) writer.WriteLine("<Note>OFF</Note>"); if(lastNote != -1) writer.WriteLine("<Volume>{0:X2}</Volume>", pulse.vol * 8); writer.WriteLine("</NoteColumn>"); writer.WriteLine("</NoteColumns>"); writer.WriteLine("</Line>"); } //close PatternTrack writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); if (TRACK == 0) { pulse0_lastNote = lastNote; pulse0_lastType = lastType; } else { pulse1_lastNote = lastNote; pulse1_lastType = lastType; } } //pulse tracks loop //triangle track generation { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); for (int i = 0; i < configuredPatternLength; i++) { int patLine = i; int index = i + time; if (index >= Log.Count) continue; var rec = Log[index]; TriangleState tri = rec.triangle; { bool keyoff = false, keyon = false; if (tri_lastNote != -1 && !tri.en) { tri_lastNote = -1; keyoff = true; } else if (tri_lastNote != tri.note && tri.en) keyon = true; if(tri.en) tri_lastNote = tri.note; writer.WriteLine("<Line index=\"{0}\">", patLine); writer.WriteLine("<NoteColumns>"); writer.WriteLine("<NoteColumn>"); if (keyon) { writer.WriteLine("<Note>{0}</Note>", NameForNote(tri.note)); writer.WriteLine("<Instrument>08</Instrument>"); } else if (keyoff) writer.WriteLine("<Note>OFF</Note>"); //no need for tons of these //if(keyon) writer.WriteLine("<Volume>80</Volume>"); writer.WriteLine("</NoteColumn>"); writer.WriteLine("</NoteColumns>"); writer.WriteLine("</Line>"); } } //close PatternTrack writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); } //noise track generation { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); for (int i = 0; i < configuredPatternLength; i++) { int patLine = i; int index = i + time; if (index >= Log.Count) continue; var rec = Log[index]; NoiseState noise = rec.noise; //transform quieted notes to dead notes //blech its buggy, im tired //if (noise.vol == 0) // noise.en = false; { bool keyoff = false, keyon = false; if (noise_lastNote != -1 && !noise.en) { noise_lastNote = -1; keyoff = true; } else if (noise_lastNote != noise.note && noise.en) keyon = true; if (noise.en) noise_lastNote = noise.note; writer.WriteLine("<Line index=\"{0}\">", patLine); writer.WriteLine("<NoteColumns>"); writer.WriteLine("<NoteColumn>"); if (keyon) { writer.WriteLine("<Note>{0}</Note>", NameForNote(noise.note)); writer.WriteLine("<Instrument>04</Instrument>"); } else if (keyoff) writer.WriteLine("<Note>OFF</Note>"); if (noise_lastNote != -1) writer.WriteLine("<Volume>{0:X2}</Volume>", noise.vol * 8); writer.WriteLine("</NoteColumn>"); writer.WriteLine("</NoteColumns>"); writer.WriteLine("</Line>"); } } //close PatternTrack writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); } //noise track generation //write empty track for now for pcm for (int TRACK = 4; TRACK < 5; TRACK++) { writer.WriteLine("<PatternTrack type=\"PatternTrack\">"); writer.WriteLine("<Lines>"); writer.WriteLine("</Lines>"); writer.WriteLine("</PatternTrack>"); } //we definitely need a dummy master track now writer.WriteLine("<PatternMasterTrack type=\"PatternMasterTrack\">"); writer.WriteLine("</PatternMasterTrack>"); //close tracks writer.WriteLine("</Tracks>"); //close pattern writer.WriteLine("</Pattern>"); time += configuredPatternLength; } //main pattern loop writer.WriteLine("</Patterns>"); writer.Flush(); var xNewPatternList = XElement.Parse(writer.ToString()); xPatternPool.Add(xNewPatternList); //write pattern sequence writer = new StringWriter(); writer.WriteLine("<SequenceEntries>"); for (int i = 0; i < patternCount; i++) { writer.WriteLine("<SequenceEntry>"); writer.WriteLine("<IsSectionStart>false</IsSectionStart>"); writer.WriteLine("<Pattern>{0}</Pattern>", i); writer.WriteLine("</SequenceEntry>"); } writer.WriteLine("</SequenceEntries>"); var xPatternSequence = templateRoot.XPathSelectElement("//PatternSequence"); xPatternSequence.XPathSelectElement("SequenceEntries").Remove(); xPatternSequence.Add(XElement.Parse(writer.ToString())); //copy template file to target File.Delete(outPath); File.Copy(templatePath, outPath); var msOutXml = new MemoryStream(); templateRoot.Save(msOutXml); msOutXml.Flush(); msOutXml.Position = 0; var zfOutput = new ICSharpCode.SharpZipLib.Zip.ZipFile(outPath); zfOutput.BeginUpdate(); zfOutput.Add(new Stupid { stream = msOutXml }, "Song.xml"); zfOutput.CommitUpdate(); zfOutput.Close(); //for easier debugging, write patterndata XML //DUMP_TO_DISK(msOutXml.ToArray()) }
//protected void Page_Load(object sender, EventArgs e) //{ // //CifrarStringConexao(); // GridViewAcerto.PreRender += GridViewAcerto_PreRender; // GridViewPrevia.PreRender += GridViewPrevia_PreRender; //} //private void GridViewPrevia_PreRender(object sender, EventArgs e) //{ // try // { // GridViewPrevia.HeaderRow.TableSection = TableRowSection.TableHeader; // } // catch (Exception) // { } //} //private void GridViewAcerto_PreRender(object sender, EventArgs e) //{ // try // { // GridViewAcerto.HeaderRow.TableSection = TableRowSection.TableHeader; // } // catch (Exception) // { } //} protected void ButtonEnviar_Click(object sender, EventArgs e) { Cache.Remove("menorAno"); Cache.Remove("ultima_atualizacao"); Cache.Remove("tableParlamentar"); Cache.Remove("tableDespesa"); Cache.Remove("tablePartido"); String atualDir = Server.MapPath("Upload"); if (FileUpload.FileName != "") { //string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"]; //string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"]; //string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"]; //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip"); //request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy. //request.Method = WebRequestMethods.Ftp.UploadFile; //request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); //StreamReader sourceStream = new StreamReader(fileToBeUploaded); //byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); //sourceStream.Close(); //request.ContentLength = fileContents.Length; //Stream requestStream = request.GetRequestStream(); //requestStream.Write(fileContents, 0, fileContents.Length); //requestStream.Close(); //FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); //response.Close(); //using (var requestStream = request.GetRequestStream()) //{ // using (var input = File.OpenRead(fileToBeUploaded)) // { // input.CopyTo(requestStream); // } //} if (!Directory.Exists(atualDir)) Directory.CreateDirectory(atualDir); FileUpload.SaveAs(atualDir + "\\" + FileUpload.FileName); ICSharpCode.SharpZipLib.Zip.ZipFile file = null; try { file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "\\" + FileUpload.FileName); if (file.TestArchive(true) == false) { Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>"); return; } } finally { if (file != null) file.Close(); } ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null); File.Delete(atualDir + "//" + FileUpload.FileName); Carregar(atualDir); } else { DirectoryInfo dir = new DirectoryInfo(atualDir); foreach (FileInfo file in dir.GetFiles("*.zip")) { ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(file.FullName, file.DirectoryName, null); File.Delete(file.FullName); Carregar(file.DirectoryName); } } }
protected void ButtonSenadores_Click(object sender, EventArgs e) { String atualDir = Server.MapPath("Upload"); if (FileUpload.FileName != "") { FileUpload.SaveAs(atualDir + "//" + FileUpload.FileName); ICSharpCode.SharpZipLib.Zip.ZipFile file = null; try { file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "//" + FileUpload.FileName); if (file.TestArchive(true) == false) { Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>"); return; } } finally { if (file != null) file.Close(); } ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null); File.Delete(atualDir + "//" + FileUpload.FileName); CarregarSenadores(atualDir); } else { DirectoryInfo dir = new DirectoryInfo(atualDir); foreach (FileInfo file in dir.GetFiles("*.zip")) { ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(file.FullName, file.DirectoryName, null); File.Delete(file.FullName); CarregarSenadores(file.DirectoryName); } } Cache.Remove("menorAnoSenadores"); Cache.Remove("ultimaAtualizacaoSenadores"); Cache.Remove("tableSenadores"); Cache.Remove("tableDespesaSenadores"); Cache.Remove("tablePartidoSenadores"); }
public static bool ScaricaUltimoDBDalWeb(maionemikyWS.EmailSending e, string yyyyMMddHHmmss, string PathDB, string email_, string psw, bool CreaNuovo) { var ok = false; var db_path = System.IO.Path.GetDirectoryName(PathDB); var zip_path = System.IO.Path.Combine(db_path, email_ + ".zip"); try { var db_bytes = e.OttieniUltimoDBRC(yyyyMMddHHmmss, email_, psw); if ((db_bytes?.Length ?? 0) > 0) { System.IO.File.WriteAllBytes(zip_path, db_bytes); if (System.IO.File.Exists(zip_path)) { var guid = System.IO.Path.Combine(db_path, Guid.NewGuid().ToString()); try { if (!CreaNuovo) { System.IO.File.Move(PathDB, guid); } try { var zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(zip_path); foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zip) { if (!zipEntry.IsFile) { continue; // Ignore directories } var entryFileName = System.IO.Path.GetFileName(zipEntry.Name); var buffer = new byte[4096]; // 4K is optimum var zipStream = zip.GetInputStream(zipEntry); // Manipulate the output filename here as desired. var fullZipToPath = System.IO.Path.Combine(db_path, entryFileName); using (var streamWriter = System.IO.File.Create(fullZipToPath)) { Copy(zipStream, streamWriter, buffer); streamWriter.Close(); } } zip.Close(); System.IO.File.Delete(guid); System.IO.File.Delete(zip_path); ok = true; } catch (Exception ex4) { System.IO.File.Move(guid, PathDB); MsgBox(ex4); } } catch (Exception ex3) { MsgBox(ex3); } } } } catch (Exception ex2) { MsgBox(ex2); } return(ok); }
public void Dispose() { if (m_zip != null) { if (m_zip.IsUpdating) m_zip.CommitUpdate(); m_zip.Close(); #if SHARPZIPLIBWORKS //This breaks, because the updates are not flushed correctly m_zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(m_zip.Name); m_zip.Close(); #endif } m_zip = null; #if !SHARPZIPLIBWORKS if (m_stream != null) { m_stream.Flush(); m_stream.Finish(); m_stream.Close(); } #endif }
//directory : end of "/" or "\\" public static bool UnZipDirectory(string zipFileName, string directory, string password = null, Action <string, float, long, long> cb = null) { try { /*if (!Directory.Exists(directory)) * Directory.CreateDirectory(directory); * directory = directory.Replace('\\', '/'); * if (directory.EndsWith("/")) * directory = directory.Substring(0, directory.Length - 1); * SharpZipLib.Zip.FastZipEvents events = new SharpZipLib.Zip.FastZipEvents(); * events.Progress += (object sender, SharpZipLib.Core.ProgressEventArgs e) => * { * if(cb != null) * { * cb(e.Name, e.PercentComplete, e.Processed, e.Target); * } * else * { * LogUtil.Log("UnZip {0} {1}/{2}--{3}",e.Name, e.Processed, e.Target,e.PercentComplete); * } * }; * SharpZipLib.Zip.FastZip fz = new SharpZipLib.Zip.FastZip(events); * fz.Password = password; * fz.ExtractZip(zipFileName,directory, SharpZipLib.Zip.FastZip.Overwrite.Always,null,null,null,true); */ if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } SharpZipLib.Zip.ZipFile szip = new SharpZipLib.Zip.ZipFile(zipFileName); szip.Password = password; long count = szip.Count; szip.Close(); SharpZipLib.Zip.ZipInputStream s = new SharpZipLib.Zip.ZipInputStream(File.OpenRead(zipFileName)); s.Password = password; SharpZipLib.Zip.ZipEntry theEntry; int n = 0; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName != string.Empty) { Directory.CreateDirectory(Path.Combine(directory, directoryName)); } if (fileName != string.Empty) { FileStream streamWriter = File.Create(Path.Combine(directory, theEntry.Name)); LogUtil.Log("-------------->Begin UnZip {0},Size:{1}", theEntry.Name, theEntry.Size); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } if (cb != null) { cb(theEntry.Name, theEntry.Size > 0 ? 100 * streamWriter.Length * 1.0f / theEntry.Size : 100, streamWriter.Length, theEntry.Size); } // else // { // LogUtil.Log("UnZip {0} {1}/{2}--{3}", theEntry.Name, streamWriter.Length, theEntry.Size, theEntry.Size > 0 ? 100*streamWriter.Length*1.0f / theEntry.Size : 100); // } } streamWriter.Close(); n++; LogUtil.Log("-------------->End UnZip {0}, {1}/{2}", theEntry.Name, n, count); } } s.Close(); return(true); } catch (Exception e) { LogUtil.LogError(e.Message); return(false); } }
/// <summary> /// 获取主配置文件信息 /// </summary> /// <param name="apkStream">apk流</param> /// <returns>安卓信息列表</returns> public static IList <AndroidInfo> GetManifestInfo(Stream apkStream) { if (apkStream == null) { throw new ArgumentNullException("apk流不能为null"); } var androidInfos = new List <AndroidInfo>(); byte[] manifestData = null; using (var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(apkStream)) { foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry item in zipfile) { if (item.Name.ToLower() == "androidmanifest.xml") { using (Stream strm = zipfile.GetInputStream(item)) { using (BinaryReader s = new BinaryReader(strm)) { manifestData = s.ReadBytes((int)item.Size); } } break; } } zipfile.Close(); } if (manifestData.IsNullOrLength0()) { return(null); } #region 读取文件内容 using (var stream = new MemoryStream(manifestData)) { using (var reader = new AndroidXmlReader(stream)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: AndroidInfo info = new AndroidInfo(); androidInfos.Add(info); info.Name = reader.Name; info.Settings = new List <KeyValueInfo <string, string> >(); for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); var setting = new KeyValueInfo <string, string>() { Key = reader.Name, Value = reader.Value }; info.Settings.Add(setting); } reader.MoveToElement(); break; } } reader.Close(); } } #endregion return(androidInfos); }
private void ExtractXmlFiles(Stream stream) { #if SILVERLIGHT StreamResourceInfo zipStream = new StreamResourceInfo(stream, null); #else ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(stream); #endif foreach (string file in FilesToDownload) { UpdateProgress(0, "Decompressing " + file + "..."); #if !SILVERLIGHT // we don't actually want ClientBin part in the zip string part = file.Remove(0, 10); StreamReader sr = new StreamReader(zipFile.GetInputStream(zipFile.GetEntry(part))); string unzippedFile = sr.ReadToEnd(); StreamWriter writer = new StreamWriter(file); writer.Write(unzippedFile); writer.Close(); #else Uri part = new Uri(file, UriKind.Relative); // This reading method only works in Silverlight due to the GetResourceStream not existing with 2 arguments in // regular .Net-land StreamResourceInfo fileStream = Application.GetResourceStream(zipStream, part); StreamReader sr = new StreamReader(fileStream.Stream); string unzippedFile = sr.ReadToEnd(); //Write it in a special way when using IsolatedStorage, due to IsolatedStorage //having a huge performance issue when writing small chunks IsolatedStorageFileStream isfs = GetFileStream(file, true); char[] charBuffer = unzippedFile.ToCharArray(); int fileSize = charBuffer.Length; byte[] byteBuffer = new byte[fileSize]; for (int i = 0; i < fileSize; i++) byteBuffer[i] = (byte)charBuffer[i]; isfs.Write(byteBuffer, 0, fileSize); isfs.Close(); #endif UpdateProgress(0, "Finished " + file + "..."); } #if !SILVERLIGHT zipFile.Close(); #endif }
private static string ExtractZip(FileInfo info) { var extractDir = Path.Combine(info.Directory.FullName, info.Name.Substring(0, info.Name.Length - info.Extension.Length)); if (!Directory.Exists(extractDir)) Directory.CreateDirectory(extractDir); var zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(info.FullName); foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zip) { var dst = Path.Combine(extractDir, entry.Name.Replace('/', Path.DirectorySeparatorChar)); if (File.Exists(dst)) File.Delete(dst); var inf = new FileInfo(dst); if (!inf.Directory.Exists) inf.Directory.Create(); using (var zipStream = zip.GetInputStream(entry)) { using (var output = File.OpenWrite(dst)) { var buffer = new byte[4096]; while (zipStream.Position < entry.Size) { var read = zipStream.Read(buffer, 0, buffer.Length); if (read > 0) output.Write(buffer, 0, read); else break; } } } } zip.Close(); return extractDir; }
public void Dispose() { zip.Close(); }
/// <summary> /// Unzip a local file and return its contents via streamreader to a local the same location as the ZIP. /// </summary> /// <param name="zipFile">Location of the zip on the HD</param> /// <returns>List of unzipped file names</returns> public static List<string> UnzipToFolder(string zipFile) { //1. Initialize: var files = new List<string>(); var slash = zipFile.LastIndexOf(Path.DirectorySeparatorChar); var outFolder = ""; if (slash > 0) { outFolder = zipFile.Substring(0, slash); } ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { var fs = File.OpenRead(zipFile); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); foreach (ZipEntry zipEntry in zf) { //Ignore Directories if (!zipEntry.IsFile) continue; //Remove the folder from the entry var entryFileName = Path.GetFileName(zipEntry.Name); if (entryFileName == null) continue; var buffer = new byte[4096]; // 4K is optimum var zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. var fullZipToPath = Path.Combine(outFolder, entryFileName); //Save the file name for later: files.Add(fullZipToPath); //Log.Trace("Data.UnzipToFolder(): Input File: " + zipFile + ", Output Directory: " + fullZipToPath); //Copy the data in buffer chunks using (var streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } return files; }
//protected void Page_Load(object sender, EventArgs e) //{ // //CifrarStringConexao(); // GridViewAcerto.PreRender += GridViewAcerto_PreRender; // GridViewPrevia.PreRender += GridViewPrevia_PreRender; //} //private void GridViewPrevia_PreRender(object sender, EventArgs e) //{ // try // { // GridViewPrevia.HeaderRow.TableSection = TableRowSection.TableHeader; // } // catch (Exception) // { } //} //private void GridViewAcerto_PreRender(object sender, EventArgs e) //{ // try // { // GridViewAcerto.HeaderRow.TableSection = TableRowSection.TableHeader; // } // catch (Exception) // { } //} protected void ButtonEnviar_Click(object sender, EventArgs e) { Cache.Remove("menorAno"); Cache.Remove("ultima_atualizacao"); Cache.Remove("tableParlamentar"); Cache.Remove("tableDespesa"); Cache.Remove("tablePartido"); String atualDir = Server.MapPath("Upload"); if (FileUpload.FileName != "") { //string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"]; //string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"]; //string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"]; //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip"); //request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy. //request.Method = WebRequestMethods.Ftp.UploadFile; //request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); //StreamReader sourceStream = new StreamReader(fileToBeUploaded); //byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); //sourceStream.Close(); //request.ContentLength = fileContents.Length; //Stream requestStream = request.GetRequestStream(); //requestStream.Write(fileContents, 0, fileContents.Length); //requestStream.Close(); //FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); //response.Close(); //using (var requestStream = request.GetRequestStream()) //{ // using (var input = File.OpenRead(fileToBeUploaded)) // { // input.CopyTo(requestStream); // } //} if (!Directory.Exists(atualDir)) { Directory.CreateDirectory(atualDir); } FileUpload.SaveAs(atualDir + "\\" + FileUpload.FileName); ICSharpCode.SharpZipLib.Zip.ZipFile file = null; try { file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "\\" + FileUpload.FileName); if (file.TestArchive(true) == false) { Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>"); return; } } finally { if (file != null) { file.Close(); } } ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null); File.Delete(atualDir + "//" + FileUpload.FileName); Carregar(atualDir); } else { DirectoryInfo dir = new DirectoryInfo(atualDir); foreach (FileInfo file in dir.GetFiles("*.zip")) { ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.ExtractZip(file.FullName, file.DirectoryName, null); File.Delete(file.FullName); Carregar(file.DirectoryName); } } }