//解密 public string Decrypt(string m,string key) { string msg = null; string[] array = m.Split('~'); int length = array.Length; byte[] by = new byte[length]; for (int i = 0; i < length;i++ ) { int l = int.Parse(array[i]); byte[] k = System.BitConverter.GetBytes(l); by[i] = k[0]; } try { FileStream aFile = new FileStream("2.txt", FileMode.Create); BinaryWriter sw = new BinaryWriter(aFile); sw.Write(by); sw.Close(); aFile.Close(); } catch (IOException e){} test.DES_Decrypt("2.txt", key, "3.txt"); try { FileStream file = new FileStream("3.txt", FileMode.Open); StreamReader read = new StreamReader(file); msg=read.ReadToEnd(); read.Close(); file.Close(); } catch (IOException) { } return msg; }
private static string DeCrypting() { var res = string.Empty; var file = new FileStream(Controller.GetPath(), FileMode.Open, FileAccess.Read, FileShare.None, 32, FileOptions.SequentialScan); var reader = new BinaryReader(file); var writer = new BinaryWriter(new FileStream(Processor.GetNewName(Controller.GetPath()), FileMode.Create, FileAccess.Write, FileShare.None, 32, FileOptions.WriteThrough)); try { var pos = 0; while (pos < file.Length) { var c = reader.ReadUInt16(); //var pow = Processor.fast_exp(c, Controller.GetKc(), Controller.GetR()); var pow = Processor.Pows(c, Controller.GetKc(), Controller.GetR()); if (pos < 256) res += pow + " "; writer.Write((byte)(pow)); pos += 2; } } finally { writer.Close(); reader.Close(); } return "Decoding Complete!\n" + res; }
static void Main(string[] args) { FileStream filStream; BinaryWriter binWriter; Console.Write("Enter name of the file: "); string fileName = Console.ReadLine(); if (File.Exists(fileName)) { Console.WriteLine("File - {0} already exists!", fileName); } else { filStream = new FileStream(fileName, FileMode.CreateNew); binWriter = new BinaryWriter(filStream); decimal aValue = 2.16M; binWriter.Write("Sample Run"); for (int i = 0; i < 11; i++) { binWriter.Write(i); } binWriter.Write(aValue); binWriter.Close(); filStream.Close(); Console.WriteLine("File Created successfully"); } Console.ReadKey(); }
public void writeBinary() { string nom = tbName.Text + ".bytes"; byte i; BinaryReader br = null; BinaryWriter bw = null; FileStream fs = null; //Ecriture d'octets dans le fichier bw = new BinaryWriter(File.Create(nom)); i = Convert.ToByte(width.Text); bw.Write(i); i = Convert.ToByte(height.Text); bw.Write(i); i = Convert.ToByte(random.Checked); bw.Write(i); for (int j = 3; j < Convert.ToInt32(width.Text); j++) { bw.Write(Convert.ToSByte(0)); } foreach (DataGridViewRow data in dataGridView1.Rows) { for(int j = 0; j < dataGridView1.Columns.Count;j++) { i = Convert.ToByte(data.Cells[j].Value); bw.Write(i); } } bw.Close(); }
public void ImportMedia(string fileUri) { var fileName = Path.GetFileName(fileUri); var savePathForFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName); if (!File.Exists(savePathForFile)) { var client = new WebClient(); BinaryWriter binaryWriter = null; try { byte[] data = client.DownloadData(fileUri); var fileStream = new FileStream(savePathForFile, FileMode.Create, FileAccess.Write); binaryWriter = new BinaryWriter(fileStream); binaryWriter.Write(data); binaryWriter.Close(); } finally { client.Dispose(); if (binaryWriter != null) { binaryWriter.Close(); } } } }
/*Initiates a TFTP file transfer from the server to the local machine.*/ public bool transfer(IPEndPoint server, String filename, bool error, TransferMode mode) { if (DEBUG) { Console.WriteLine("Retrieving file " + filename + " from server at " + server.ToString() + (error ? " with errors " : " without errors ") + "using transfer mode " + (mode == TransferMode.NETASCII ? "netascii." : "octet.")); } IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); byte[] block; byte[] message = new byte[416]; UInt16 blocknum; Int32 msgBytes = 0; Int32 index = 0; BinaryWriter fileWriter; UdpClient client = new UdpClient(); fileWriter = new BinaryWriter(File.Create(filename, 512)); requestData(client, server, filename, error, mode); do { block = recieveData(client, ref sender); if (DEBUG) { Console.WriteLine("Recieved datagram with length " + block.Length + " from " + sender.ToString() + "with op code " + HammingCode.getOpCode(block) + ":\n" + ASCII.GetString(block)); } if (HammingCode.getOpCode(block) == 3) { blocknum = HammingCode.getBlockNum(block); if (DEBUG) { Console.WriteLine("Recieved data packet with block number: " + blocknum); } if (HammingCode.getMessage(block, block.Length, ref message, ref msgBytes)) { fileWriter.Write(message, 0, msgBytes); index += msgBytes; acknowledge(client, sender, blocknum); } else { nacknowledge(client, sender, blocknum); continue; } } else if (HammingCode.getOpCode(block) == 5) //error { Console.WriteLine("Error encountered. Terminating file transfer."); client.Close(); fileWriter.Close(); File.Delete(filename); return false; } else //wtf? { Console.WriteLine("Recieved packet with unexpected op code. Terminating file transfer."); client.Close(); fileWriter.Close(); File.Delete(filename); return false; } } while (block.Length > 515); fileWriter.Close(); return true; }
public static void Decrypt(string file_input, string file_output, string key1) { FileStream input; BinaryReader br; FileStream output; BinaryWriter bw; byte[] block; key = new Key(key1); Utils.key.makeKey(); Utils.key.reverseKey(); try { input = new FileStream(file_input, FileMode.Open, FileAccess.Read); br = new BinaryReader(input); output = new FileStream(file_output, FileMode.Create, FileAccess.Write); bw = new BinaryWriter(output); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } //// try { while ((block = br.ReadBytes(8)).Length > 0) { BitArray encrypted_message = Utils.makeMessage(napraw(block)); bw.Write((encrypted_message.ToByteArray())); } } catch (Exception ex) { MessageBox.Show(ex.Message); input.Close(); output.Close(); br.Close(); bw.Close(); } finally { input.Close(); output.Close(); br.Close(); bw.Close(); } }
public void AddBook(string author, string title, string pubHouse, int pubYear) { for (int i = 0; i < BookList.Count; i++) { if (author == BookList[i].Author && title == BookList[i].Title) { TheSameIsExistException ex = new TheSameIsExistException(); logger.Info(ex.Message); logger.Info(ex.StackTrace); throw ex; } } BookList.Add(new Book(author, title, pubHouse, pubYear)); try { writer = new BinaryWriter(new FileStream("C:/BookData.bin", FileMode.Append)); writer.Write(BookList[BookList.Count - 1].Author); writer.Write(BookList[BookList.Count - 1].Title); writer.Write(BookList[BookList.Count - 1].PublishingHouse); writer.Write(BookList[BookList.Count - 1].PublishingYear); } catch (IOException ex) { logger.Info(ex.Message); logger.Info(ex.StackTrace); Debug.WriteLine("IOException: " + ex.Message); } finally { writer.Close(); } }
public static void DoAcceptTcpClientCallback(IAsyncResult ar) { Thread.Sleep(0); Byte[] bytes = new Byte[1024]; String data = null; TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); Console.WriteLine("Client connect completed"); data = null; NetworkStream stream = client.GetStream(); BinaryFormatter outformat = new BinaryFormatter(); string name; name = outformat.Deserialize(stream).ToString(); FileStream fs = new FileStream("D:\\" + name, FileMode.OpenOrCreate); BinaryWriter bw = new BinaryWriter(fs); int count; count = int.Parse(outformat.Deserialize(stream).ToString()); int i = 0; for (; i < count; i += 1024) { byte[] buf = (byte[])(outformat.Deserialize(stream)); bw.Write(buf); } Console.WriteLine("Successfully read in D:\\" + name); bw.Close(); fs.Close(); tcpClientConnected.Set(); }
public void WriteFile(string file) { BinaryWriter bw = new BinaryWriter(File.OpenWrite(file)); WriteFile(bw); bw.Flush(); bw.Close(); }
private void OnDownloadComplete(object sender, DownloadDataCompletedEventArgs e) { try { if (!e.Cancelled) { while (File.Exists(Destination)) { string[] temp = Destination.Split('.'); Destination = temp[0] + "_." + temp[1]; } BinaryWriter bw = new BinaryWriter(new FileStream(Destination, FileMode.CreateNew)); bw.Write(e.Result); bw.Close(); } CallProcess(new ExcutionResult(ResultFlag.Result, "", "Download complete :\r\n" + Destination)); DownloadCmdList.Remove(this); }catch(Exception ex) { CallProcess(new ExcutionResult(ResultFlag.Error, "", "Download Error :\r\n" + ex.ToString())); DownloadCmdList.Remove(this); } }
/// <summary> /// Send information about this CityServer to the LoginServer... /// </summary> /// <param name="Client">The client connected to the LoginServer.</param> public static void SendServerInfo(NetworkClient Client) { PacketStream Packet = new PacketStream(0x64, 0); Packet.WriteByte(0x64); MemoryStream PacketBody = new MemoryStream(); BinaryWriter PacketWriter = new BinaryWriter(PacketBody); PacketWriter.Write((string)GlobalSettings.Default.CityName); PacketWriter.Write((string)GlobalSettings.Default.CityDescription); PacketWriter.Write((string)Settings.BINDING.Address.ToString()); PacketWriter.Write((int)Settings.BINDING.Port); PacketWriter.Write((byte)1); //CityInfoStatus.OK PacketWriter.Write((ulong)GlobalSettings.Default.CityThumbnail); PacketWriter.Write((string)GlobalSettings.Default.ServerID); PacketWriter.Write((ulong)GlobalSettings.Default.Map); PacketWriter.Flush(); Packet.WriteUInt16((ushort)(PacketBody.ToArray().Length + PacketHeaders.UNENCRYPTED)); Packet.Write(PacketBody.ToArray(), 0, (int)PacketWriter.BaseStream.Length); Packet.Flush(); PacketWriter.Close(); Client.Send(Packet.ToArray()); }
private void binaryCodeHEXToolStripMenuItem_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "Binary Code File |*.hex"; saveFileDialog1.Title = "Save Pattern Hex Code"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) using (FileStream hex = new FileStream(saveFileDialog1.FileName, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(hex)) { int row = 0, col = 0, page = 0; byte z=0; for (page = 0; page <= dataGridView1.RowCount / 8; page++) for (col = 0; col < dataGridView1.ColumnCount; col++) { for (row = 0; row < 8; row++) { if (dataGridView1.RowCount > (page * 8) + row) if (dataGridView1.Rows[(page * 8) + row].Cells[col].Style.BackColor == Color.Black) z = Convert.ToByte(z + Math.Pow(2.0, row)); z += 0; } writer.Write(z); z = 0; } writer.Close(); } } saveFileDialog1.Filter = "Matrix Pattern Files|*.maz"; saveFileDialog1.Title = "Save Pattern File"; saveFileDialog1.FileName = ""; }
/// <summary> /// Al pulsar el boton de Aceptar, para guardar cambios de configuracion /// </summary> private void BConfig_Aceptar_Click(object sender, EventArgs e) { // Solo hace falta guardar cambios si se ha modificado un dato if(_CModificada) { Globl.Config.Nick = TB_Config_Nick.Text; Globl.Config.EMail = TB_Config_EMail.Text; Globl.Config.ReqPass = CBConfig_Recordar.Checked; FileStream stream = new FileStream(@"Usuarios\" + Globl.Config.Usuario + @"\config.dat", FileMode.Create); BinaryWriter writer = new BinaryWriter(stream); writer.Write(Globl.Config.Nick); writer.Write(Globl.Config.EMail); writer.Write(Globl.Config.PassMD5); writer.Write(Globl.Config.ReqPass); writer.Close(); } if(_ImgCambiada) { File.Delete(@"Perfiles\" + Globl.Config.Usuario + ".png"); File.Copy(OPFConfig_CambiarImg.FileName, @"Perfiles\" + Globl.Config.Usuario + ".png"); } PBConfig_Perfil.Image.Dispose(); PBConfig_Perfil.Dispose(); this.Close(); }
private static IEnumerable<byte> MakeWaveHeader(WaveProcessor Wave) { MemoryStream fs = new MemoryStream(); BinaryWriter bw = new BinaryWriter(fs); fs.Position = 0; bw.Write(new[] { 'R', 'I', 'F', 'F' }); bw.Write(Wave.Length); bw.Write(new[] { 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ' }); bw.Write(16); bw.Write((short)1); bw.Write(Wave.Channels); bw.Write(Wave.SampleRate); bw.Write((Wave.SampleRate * ((Wave.BitsPerSample * Wave.Channels) / 8))); bw.Write((short)((Wave.BitsPerSample * Wave.Channels) / 8)); bw.Write(Wave.BitsPerSample); bw.Write(new[] { 'd', 'a', 't', 'a' }); bw.Write(Wave.DataLength); bw.Close(); Byte[] Result = fs.ToArray(); fs.Close(); return Result; }
/// <summary> /// Checks if the new score just got is higher than the old highscore, if it is the file is overwritten with the new high score /// </summary> /// <param name="score">the score for the level just lost</param> static void checkScore(int score) { if (Game1.Instance.HighScore < score) { BinaryWriter writer = null; try { writer = new BinaryWriter(File.Open("HighScore.score", FileMode.Create)); writer.Write((Int32)score); Game1.Instance.HighScore = score; } catch { Game1.Instance.spriteBatch.Begin(); Game1.Instance.spriteBatch.DrawString(Game1.font, "Cannot Save HighScore", Game1.Cent - Game1.font.MeasureString("Cannot Save HighScore"), Color.White); Game1.Instance.spriteBatch.End(); } finally { if( writer != null )writer.Close(); } } }
public void WaveHeaderOUT(string sPath) { FileStream fs = new FileStream(sPath, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); fs.Position = 0; bw.Write(new char[4] { 'R', 'I', 'F', 'F' }); bw.Write(length); bw.Write(new char[8] { 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ' }); bw.Write((int)16); bw.Write((short)1); bw.Write(channels); bw.Write(samplerate); bw.Write((int)(samplerate * ((BitsPerSample * channels) / 8))); bw.Write((short)((BitsPerSample * channels) / 8)); bw.Write(BitsPerSample); bw.Write(new char[4] { 'd', 'a', 't', 'a' }); bw.Write(DataLength); bw.Close(); fs.Close(); }
public static void SaveStreamToFile(Stream FromStream, string TargetFile) { // FromStream=the stream we wanna save to a file //TargetFile = name&path of file to be created to save to //i.e"c:\mysong.mp3" try { //Creat a file to save to Stream ToStream = File.Create(TargetFile); //use the binary reader & writer because //they can work with all formats //i.e images, text files ,avi,mp3.. BinaryReader br = new BinaryReader(FromStream); BinaryWriter bw = new BinaryWriter(ToStream); //copy data from the FromStream to the outStream //convert from long to int bw.Write(br.ReadBytes((int)FromStream.Length)); //save bw.Flush(); //clean up bw.Close(); br.Close(); } //use Exception e as it can handle any exception catch (Exception e) { //code if u like } }
protected void AsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e) { byte[] imageData; using (Stream stream = e.File.InputStream) { imageData = new byte[stream.Length]; stream.Read(imageData, 0, (int)stream.Length); } //save image string file = Server.MapPath("/Files/Verification/") + "\\" + e.File.FileName; //AsyncUpload1.UploadedFiles[0].SaveAs(file); string fullurl = Request.Url.AbsoluteUri; //string saveimgurl = //fullurl.Substring(0, fullurl.ToLower().IndexOf("order_form2.aspx")) + Thumbnail.ImageUrl.Replace("~/", ""); //sitetemp.savepicurl2(saveimgurl, file); FileStream fs = new FileStream(file, FileMode.Create); BinaryWriter w = new BinaryWriter(fs); try { w.Write(imageData); } finally { fs.Close(); w.Close(); } }
static void Main(string[] args) { string output = string.Empty; //define test soils SoilParam[] soils = new SoilParam[2]; soils[0] = new SoilParam(10, 103, 0.4, 2.0, -2.0, -10.0, 1.0 / 3.0, 1.0); soils[1] = new SoilParam(10, 109, 0.6, 0.2, -2.0, -40.0, 1.0 / 9.0, 1.0); string[] ftname = new string[2]; int[] sidx; int i, j; int[] ndz; double dzmin; double[] x; double[,] dz = new double[2, 10]; //only for testing? if not will need to change hardcoded dimensions. bool Kgiven = false; SoilProps sp1, sp2; FluxTable ft1, ft2; //define soil profile x = new double[] {10,20,30,40,60,80,100,120,160,200}; //length = num soil layers sidx = new int[] { 103, 103, 103, 103, 109, 109, 109, 109, 109, 109 }; //soil ident of layers dzmin = 1.0; // smallest likely path length ndz = new int[] { 2, 4 }; // for the two soil types - gives six flux tables //can be done in loops, but clearer this way and will only be used for testing dz[0, 0] = 5; dz[0, 1] = 10; dz[1, 0] = 10; dz[1, 1] = 20; dz[1, 2] = 30; dz[1, 4] = 40; for (i = 0; i < 2; i++) { BinaryWriter b = new BinaryWriter(File.OpenWrite("soil" + soils[i].sid + ".dat")); MVG.Params(soils[i].sid, soils[i].ths, soils[i].ks, soils[i].he, soils[i].hd, soils[i].p, soils[i].hg, soils[i].em, soils[i].en); soils[i].sp = Soil.gensptbl(dzmin, soils[i], Kgiven); b.Write(soils[i].sid); WriteProps(b, soils[i].sp); b.Close(); for (j = 0; j < ndz[i]; j++) { Fluxes.FluxTable(dz[i, j], soils[i].sp); b = new BinaryWriter(File.OpenWrite("soil" + soils[i].sid + "dz" + dz[i, j] * 10)); b.Write(soils[i].sid); WriteFluxes(b, Fluxes.ft); b.Close(); } } //generate and write composite flux table for path with two soil types sp1 = ReadProps("soil103.dat"); sp2 = ReadProps("soil109.dat"); ft1 = ReadFluxes("soil103dz50.dat"); ft2 = ReadFluxes("soil103dz100.dat"); FluxTable ftwo = TwoFluxes.TwoTables(ft1, sp1, ft2, sp2); BinaryWriter bw = new BinaryWriter(File.OpenWrite("soil0103dz0050_soil0109dz0100.dat")); WriteFluxes(bw, ftwo); }
public static byte[] UncompressStream(Stream stream, int filesize, int memsize) { BinaryReader r = new BinaryReader(stream); long end = stream.Position + filesize; byte[] uncdata = new byte[memsize]; BinaryWriter bw = new BinaryWriter(new MemoryStream(uncdata)); byte[] data = r.ReadBytes(2); if (checking) if (data.Length != 2) throw new InvalidDataException("Hit unexpected end of file at " + stream.Position); int datalen = (((data[0] & 0x80) != 0) ? 4 : 3) * (((data[0] & 0x01) != 0) ? 2 : 1); data = r.ReadBytes(datalen); if (checking) if (data.Length != datalen) throw new InvalidDataException("Hit unexpected end of file at " + stream.Position); long realsize = 0; for (int i = 0; i < data.Length; i++) realsize = (realsize << 8) + data[i]; if (checking) if (realsize != memsize) throw new InvalidDataException(String.Format( "Resource data indicates size does not match index at 0x{0}. Read 0x{1}. Expected 0x{2}.", stream.Position.ToString("X8"), realsize.ToString("X8"), memsize.ToString("X8"))); while (stream.Position < end) { Dechunk(stream, bw); } if (checking) if (bw.BaseStream.Position != memsize) throw new InvalidDataException(String.Format("Read 0x{0:X8} bytes. Expected 0x{1:X8}.", bw.BaseStream.Position, memsize)); bw.Close(); return uncdata; }
private void DownloadAttachment(Guid attId) { IUserAttachmentService srv = ServiceFactory.GetUserAttachmentService(); UserAttachment attachment = srv.UserAttachmentSelectFile(attId); System.String disHeader; Response.Clear(); if (attachment.Path.ToLower().EndsWith(".pdf")) { Response.ContentType = "application/pdf"; disHeader = "inline;Filename=\"" + attachment.Path + "\""; } else { Response.ContentType = "APPLICATION/OCTET-STREAM"; disHeader = "Attachment;Filename=\"" + attachment.Path + "\""; } if (attachment.FileData == null || attachment.FileData.Length == 0) { throw new ApplicationException("A megtekinteni kívánt file nem létezik"); } Response.AppendHeader("Content-Disposition", disHeader); Response.AppendHeader("Content-Length", attachment.FileData.Length.ToString()); BinaryWriter writer = new BinaryWriter(Response.OutputStream); writer.Write(attachment.FileData); writer.Close(); }
public static void Save(Player player) { if (player == null) { logger.Error("Failed to save Player because no Player exists."); return; } string name = player.Name; if (name == null) { logger.Warn("Player has no name. Using name Anonymous as a fallback. Player cannot be guaranteed to have been saved properly."); name = "Anonymous"; } string tempFile = name + ".dat"; using(FileStream stream = new FileStream(tempFile, FileMode.Create)) using (BinaryWriter writer = new BinaryWriter(stream)) { try { PlayerUnloader.unload(player, writer); } finally { stream.Close(); writer.Close(); } } string targetFile = name + ".plr"; Encrypt(tempFile, targetFile); File.Delete(tempFile); }
public void SaveDBCFile() { String path = "Export/CreatureDisplayInfo.dbc"; Directory.CreateDirectory(Path.GetDirectoryName(path)); if (File.Exists(path)) File.Delete(path); FileStream fileStream = new FileStream(path, FileMode.Create); BinaryWriter writer = new BinaryWriter(fileStream); int count = Marshal.SizeOf(typeof(DBC_Header)); byte[] buffer = new byte[count]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(header, handle.AddrOfPinnedObject(), true); writer.Write(buffer, 0, count); handle.Free(); for (UInt32 i = 0; i < header.RecordCount; ++i) { count = Marshal.SizeOf(typeof(DBC_Record)); buffer = new byte[count]; handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(body.records[i], handle.AddrOfPinnedObject(), true); writer.Write(buffer, 0, count); handle.Free(); } writer.Write(Encoding.UTF8.GetBytes(body.StringBlock)); writer.Close(); fileStream.Close(); }
//����Voiceage��˾-G.729���� public unsafe byte[] Encode(byte[] data) { MemoryStream src=new MemoryStream(data); System.IO.BinaryReader brsrc=new BinaryReader(src); MemoryStream dst=new MemoryStream(); System.IO.BinaryWriter bwdst=new BinaryWriter(dst); int step=(int)(data.Length/160); for(int i=0;i<step;i++) { byte[] d=new byte[10]; for(int k=0;k<d.Length;k++) { d[k]=1; } byte[] o=brsrc.ReadBytes(160); va_g729a_encoder(o,d); bwdst.Write(d); } byte[] ret=dst.GetBuffer(); brsrc.Close(); bwdst.Close(); src.Close(); dst.Close(); return ret; }
public static string DecodeRaw(byte[] protobuf) { string retval = string.Empty; var procStartInfo = new ProcessStartInfo(); procStartInfo.WorkingDirectory = PROTOC_DIR; procStartInfo.FileName = PROTOC; procStartInfo.Arguments = @"--decode_raw"; procStartInfo.RedirectStandardInput = true; procStartInfo.RedirectStandardError = true; procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; Process proc = Process.Start(procStartInfo); // proc.StandardInput.BaseStream.Write(protobufBytes, 0, protobufBytes.Length); var binaryWriter = new BinaryWriter(proc.StandardInput.BaseStream); binaryWriter.Write(protobuf); binaryWriter.Flush(); binaryWriter.Close(); retval = proc.StandardOutput.ReadToEnd(); return retval; }
public void AddWordOccurrence(WordOccurrenceNode wordOccur) { invertedfileName = GetFileName(wordOccur.Word.WordID); //create the file or add entry to file try { bw = new BinaryWriter(new FileStream(invertedfileName, FileMode.Append)); bw.Write(wordOccur.Doc.DocID); bw.Write(wordOccur.QuantityHits); foreach (WordHit hit in wordOccur.Hits) { bw.Write(hit.Position); } } catch (IOException e) { Console.WriteLine("\n Cannot create file or write to file." + e.Message); return; } finally { bw.Close(); } }
public static void Main1(string[] args) { ITestRPC server = XmlRpcProxyGen.Create<ITestRPC>(); XmlRpcClientProtocol protocol; protocol = (XmlRpcClientProtocol)server; protocol.Url = "http://localhost:8000"; string a = server.test(); Console.WriteLine ("{0}", a); FileStream fs = new FileStream("1.zip", FileMode.Open); //获取文件大小 long size = fs.Length; byte[] array = new byte[size]; //将文件读到byte数组中 fs.Read(array, 0, array.Length); fs.Close(); byte[] bytes = server.filesave("2.zip", array); //实例化一个文件流--->与写入文件相关联 FileStream fo=new FileStream("333.zip", FileMode.Create); //实例化BinaryWriter BinaryWriter bw = new BinaryWriter(fo); bw.Write(bytes); //清空缓冲区 bw.Flush(); //关闭流 bw.Close(); fo.Close(); Console.ReadLine(); Console.ReadLine(); }
public void GetMemberInfo(string id) { IList<Hashtable> listMembers = br.GetmemberInfo(id, 0); IList<Hashtable> list = null; string imgs = ""; if (listMembers != null) { list = br.GetmemberInfo(id, 1); Hashtable htb = new Hashtable(); htb = listMembers[0]; if (htb["B_ATTACHMENT"] != null && htb["B_ATTACHMENT"].ToString() != "") { byte[] imgBytes = (byte[])(htb["B_ATTACHMENT"]); string filePath = "../Files/" + htb["T_USERID"] + ".jpg"; imgs = filePath; filePath = Server.MapPath(filePath); BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.OpenOrCreate)); bw.Write(imgBytes); bw.Close(); } } obj = new { img = imgs, list = list, }; string result = JsonConvert.SerializeObject(obj); Response.Write(result); Response.End(); }
protected void Page_Load(object sender, EventArgs e) { if (HttpContext.Current.Session["condominio"] != null) { if (Request.QueryString["id"] != null) { var idDocumento = Request.QueryString["id"].Trim(); var fileName = "documenti/" + idDocumento + ".pdf"; if(!File.Exists(Request.PhysicalApplicationPath + fileName)) { var service = new SferaService(); var info = new UserInfo(0, 1); var documento = service.GetDocumentoByIdentificativo(idDocumento, info); var docInfo = service.GetDocument(documento.ID, TipoDocumentoArchiviazione.FatturaPassiva, info); var fs = File.Create(Request.PhysicalApplicationPath + fileName); var writer = new BinaryWriter(fs); writer.Write(docInfo.Body); writer.Close(); fs.Close(); fs.Dispose(); } documentFrame.Attributes.Add("src", fileName); } } }
/// <summary> /// 收到监听请求回调 /// </summary> /// <param name="ia"></param> public void GetContextAsyncCallback(IAsyncResult ia) { if (ia.IsCompleted) { var ctx = listerner.EndGetContext(ia); ctx.Response.StatusCode = 200; if (ResponseEvent != null) { ResponseEvent.BeginInvoke(ctx, null, null); } else { System.IO.BinaryWriter br = new System.IO.BinaryWriter(ctx.Response.OutputStream, new UTF8Encoding()); br.Write("error: 服务器未处理"); ctx.Response.Close(); br.Close(); br.Dispose(); } } listerner.BeginGetContext(ac, null); }
public void Stop() { if (m_Recorder != null) { try { bw_tmp.Close(); m_Recorder.Dispose(); WriteToFile(); _recordSize = 0; _isRecord = false; } finally { m_Recorder = null; } } }
public IEnumerable <ISOSpatialRow> Write(string fileName, List <WorkingData> meters, IEnumerable <SpatialRecord> spatialRecords) { if (spatialRecords == null) { return(null); } using (var memoryStream = new MemoryStream()) { foreach (var spatialRecord in spatialRecords) { WriteSpatialRecord(spatialRecord, meters, memoryStream); } var binaryWriter = new System.IO.BinaryWriter(File.Create(fileName)); binaryWriter.Write(memoryStream.ToArray()); binaryWriter.Flush(); binaryWriter.Close(); } return(null); }
private static bool StringToFile(string base64String, string fileName) { try { //string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"/beapp/" + fileName; System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs); if (!string.IsNullOrEmpty(base64String) && File.Exists(fileName)) { bw.Write(Convert.FromBase64String(base64String)); } bw.Close(); fs.Close(); return(true); } catch { return(false); } }
//把manifest对象转为字节流 public static byte[] GetBytesFromManifest(ManifestInfo manifestInfo) { try { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms); bw.Write(manifestInfo.version); bw.Write(manifestInfo.assetDic.Count); foreach (var kv in manifestInfo.assetDic) { bw.Write(kv.Value.SubPath); bw.Write(kv.Value.Length); bw.Write(kv.Value.CreateDate); bw.Write(kv.Value.md5); bw.Write(kv.Value.Suffix); bw.Write(kv.Value.FilePathList.Count); for (int i = 0, count = kv.Value.FilePathList.Count; i < count; i++) { bw.Write(kv.Value.FilePathList[i]); } } ms.Position = 0; int len = (int)ms.Length;//manifest文件不能超2GB byte[] bytes = new byte[len]; ms.Read(bytes, 0, len); bw.Close(); ms.Close(); ms.Dispose(); //return bytes.Compress(); return(bytes); } catch (Exception e) { Debugger.LogError("GetBytesFromManifest:" + e); } finally { } return(null); }
/// <summary> /// 每个表单独导出一份bytes,可以给后端用 /// </summary> static void ExportExcelConfig() { string serverConfigProtoPath = PlayerPrefs.GetString(ExcelPathKey); if (string.IsNullOrEmpty(serverConfigProtoPath)) { Debug.Log("没有设置服务器SNV目录"); return; } DirectoryInfo serverDirectoryInfo = new DirectoryInfo(serverConfigProtoPath); System.IO.FileInfo[] serverFileInfos = serverDirectoryInfo.GetFiles("*.xlsx", SearchOption.TopDirectoryOnly); foreach (System.IO.FileInfo fileInfo in serverFileInfos) { if (fileInfo.Name.StartsWith("~")) { continue; } var start = Time.realtimeSinceStartup;//System.DateTime.Now.Ticks; string fullName = fileInfo.Name; string name = fileInfo.Name.Replace(".xlsx", ""); System.Object configObj = CreateData(serverConfigProtoPath + "/" + fullName, name); System.IO.MemoryStream MstreamConfig = new System.IO.MemoryStream(); ProtoBuf.Serializer.Serialize(MstreamConfig, configObj); byte[] dataConfig = MstreamConfig.ToArray(); var pathConfig = serverConfigProtoPath + "/" + name + ".bytes"; System.IO.FileStream FstreamConfig = System.IO.File.Create(pathConfig); System.IO.BinaryWriter bwConfig = new System.IO.BinaryWriter(FstreamConfig); bwConfig.Write(dataConfig); FstreamConfig.Close(); bwConfig.Close(); MstreamConfig.Close(); } AssetDatabase.Refresh(); }
public static bool CopyBinaryFile(string srcfilename, string destfilename) { if (System.IO.File.Exists(srcfilename) == false) { Debug.Log("Could not find The Source file " + srcfilename); return(false); } if (System.IO.File.Exists(destfilename) == true) { return(false); } System.IO.Stream s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open); System.IO.Stream s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create); System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1); System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2); while (true) { byte[] buf = new byte[10240]; int sz = f1.Read(buf, 0, 10240); if (sz <= 0) { break; } f2.Write(buf, 0, sz); if (sz < 10240) { break; // eof reached } } f1.Close(); f2.Close(); return(true); }
private void DiodTestForm_Load(object sender, EventArgs e) { form1.changeEvStatusLbl = 0; switch (form1.IGFLAG) { case 0: TimeWaitPD3Check.Value = 2; waitBeforNext.Value = 2; break; case 1: TimeWaitPD3Check.Value = 1; waitBeforNext.Value = 1; break; } form1.statusLblText("Запущена прозвонка дидов!", 2); if (System.IO.File.Exists("template.xlsx") == false) { MessageBox.Show("No template found. Creating new template file..."); System.IO.StreamWriter OutStream; System.IO.BinaryWriter BinStream; OutStream = new System.IO.StreamWriter("template.xlsx", false); BinStream = new System.IO.BinaryWriter(OutStream.BaseStream); BinStream.Write(Module_Burn_inTool.Properties.Resources.template); BinStream.Close(); } txtReportFile.Text = logDirectory; SetPD3Drop.Value = Module_Burn_inTool.Properties.Settings.Default.SetPD3Drop; TimeWaitPD3Check.Value = Module_Burn_inTool.Properties.Settings.Default.TimeWaitPD3Check; if (form1.averagingPD3_Value > 1) { SystemSounds.Beep.Play(); oldAveraging = form1.averagingPD3_Value; form1.averagingPD3_Value = (decimal)1; } deviationDeltaPD3.Value = deviationDeltaValue; }
public static void SendItemToPlayer(Item item, string playerID, int amount = 1) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(26); w.Write(playerID); w.Write(item.ID); w.Write(amount); w.Write(item.level); foreach (ItemStat stat in item.Stats) { w.Write(stat.StatID); w.Write(stat.Amount); } w.Close(); } ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone); answerStream.Close(); } }
public void saveJob(string name) { bool binary = checkBinary.Checked; bool startend = checkIncludeStartEnd.Checked; System.IO.BinaryWriter file = new System.IO.BinaryWriter(File.Open(name, FileMode.Create)); if (startend) { writeArray(file, Main.main.editor.getContentArray(1), binary); } writeArray(file, Main.main.editor.getContentArray(0), binary); if (startend) { writeArray(file, Main.main.editor.getContentArray(2), binary); } if (checkIncludeJobFinished.Checked) { PrinterConnection con = Main.conn; if (con.afterJobDisableExtruder) { writeString(file, "M104 S0", binary); } if (con.afterJobDisablePrintbed) { writeString(file, "M140 S0", binary); } if (con.afterJobGoDispose) { writeString(file, "G90", binary); writeString(file, "G1 X" + con.disposeX.ToString(GCode.format) + " Y" + con.disposeY.ToString(GCode.format) + " F" + con.travelFeedRate.ToString(GCode.format), binary); } if (con.afterJobDisableMotors) { writeString(file, "M84", binary); } } file.Close(); }
/********************************** * 函数名称:RemoteSave * 功能说明:保存远程文件 * 参 数:Url:远程url;Path:保存到的路径 * 调用示例: * GetRemoteObj o = new GetRemoteObj(); * string s = ""; * string url = @"http://www.zhaobus.net/images/zhaobus.jpg"; * string path =Server.MapPath("Html/"); * s = o.RemoteSave(url,path); * Response.Write(s); * o.Dispose(); * ******************************/ /// <summary> /// 保存远程文件 /// </summary> /// <param name="Url">远程url</param> /// <param name="Path">保存到的路径</param> /// <returns></returns> public string RemoteSave(string Url, string charset, string Path) { string src = GetRemoteHtmlCode(Url, charset); Random ra = new Random(); string StringFileName = DateRndName(ra) + "." + GetFileExtends(Url); string StringFilePath = Path + StringFileName; /* * * * * MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass(); * _xmlhttp.open("GET", Url, false, null, null); * _xmlhttp.send(""); * * if (_xmlhttp.readyState == 4) */ if (!src.IsNullOrEmpty()) { if (System.IO.File.Exists(StringFilePath)) { System.IO.File.Delete(StringFilePath); } System.IO.FileStream fs = new System.IO.FileStream(StringFilePath, System.IO.FileMode.CreateNew); System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs); //w.Write((byte[])_xmlhttp.responseBody); w.Write(src); w.Close(); fs.Close(); } //else // throw new Exception(_xmlhttp.statusText); return(StringFileName); }
private void buttonNexQuestion1_Click(object sender, EventArgs e) { var reader = new System.IO.BinaryReader( System.IO.File.OpenRead(@"C:\Users\diman\Documents\GitHub\proektpraktukym\nstudents.txt")); int nstudents = reader.ReadInt32(); reader.Close(); nstudents += 1; var writer2 = new System.IO.BinaryWriter( System.IO.File.Open(@"C:\Users\diman\Documents\GitHub\proektpraktukym\nstudents.txt", System.IO.FileMode.Create)); writer2.Write(nstudents); writer2.Close(); string vidpovid = textBox1.Text; if (vidpovid == "c") { Program.bal += 1; } var writer = new System.IO.BinaryWriter( System.IO.File.Open(@"C:\Users\diman\Documents\GitHub\proektpraktukym\rate_info.txt", System.IO.FileMode.Append, FileAccess.Write)); writer.Write(Program.pib); writer.Write(Program.grupa); writer.Write(Program.bal); writer.Close(); Result rslt = new Result(); rslt.Show(); Close(); }
protected byte [] UnCompress(byte [] body) { byte [] byRes = null; byte [] byTemp = null; System.IO.MemoryStream inMemStream = new System.IO.MemoryStream(body, 0, body.Length); System.IO.MemoryStream outMemStream = new System.IO.MemoryStream(); try { System.IO.BinaryWriter dataWriter; System.IO.BinaryReader dataReader; ZLibStream zipStream = new ZLibStream(inMemStream, CompressionMode.Decompress, CompressionLevel.Level9); dataReader = new BinaryReader(zipStream); dataWriter = new System.IO.BinaryWriter(outMemStream); CopyStream(dataReader, dataWriter); dataWriter.Flush(); byTemp = outMemStream.GetBuffer(); byRes = new byte[outMemStream.Length]; Array.Copy(byTemp, 0, byRes, 0, outMemStream.Length); dataWriter.Close(); dataReader.Close(); } catch (Exception e) { byRes = null; } finally { outMemStream.Close(); inMemStream.Close(); } return(byRes); }
public void SendRoomMessage(UInt32 roomId, String roleId, XLua.LuaTable message) { if (!this.IsConnect) { UnityEngine.Debug.LogError("SendRoomMessage this.IsConnect == False"); return; } var luaMessage = new FastNet.LocalMessage(message); var roomMessageReq = new pkt.protocols.RoomMessageReq(); roomMessageReq.clsId = luaMessage.luaTable.Get <String, UInt32>("ClsId"); roomMessageReq.roomId = roomId; roomMessageReq.roleId = roleId; roomMessageReq.signId = luaMessage.luaTable.Get <String, UInt32>("SignId"); try { var memoryStream = new System.IO.MemoryStream(); var binaryWriter = new System.IO.BinaryWriter(memoryStream, Encoding.ASCII); luaMessage.Serialize(binaryWriter); binaryWriter.Flush(); roomMessageReq.data = Encoding.ASCII.GetString(memoryStream.ToArray()); binaryWriter.Close(); memoryStream.Close(); lock (m_sendMessages) { m_sendMessages.Enqueue(roomMessageReq); } } catch (Exception e) { UnityEngine.Debug.LogException(e); } }
private void ProcesarArchivo(string Ruta, byte[] Datos, string MsjError, int Numero_Prestamo, int Anno, string Tipo) { try { if (MsjError == "") { string Archivo = Path.Combine(Ruta, "Const_" + Numero_Prestamo.ToString() + "_" + Anno.ToString() + "_" + Tipo + ".pdf"); System.IO.BinaryWriter binWriter = new System.IO.BinaryWriter(System.IO.File.Open(Archivo, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite)); binWriter.Write(Datos); binWriter.Close(); clsBD.RegistrarLog(Numero_Prestamo, Anno, Tipo, "Success", MsjError); clsBD.RegistrarArchivo(Anno, Numero_Prestamo, Tipo, "Const_" + Numero_Prestamo.ToString() + "_" + Anno.ToString() + "_" + Tipo + ".pdf"); } else { clsBD.RegistrarLog(Numero_Prestamo, Anno, Tipo, "Warning", MsjError); } } catch (Exception ex) { clsBD.RegistrarLog(Numero_Prestamo, Anno, Tipo, "Error", ex.Message); } }
/// <summary> /// Writes to binary file. /// </summary> /// <param name="filename">Filename.</param> /// <param name="content">Content.</param> /// <returns></returns> public static bool WriteToBinaryFile(string filename, byte[] content) { try { if (File.Exists(filename)) { File.Delete(filename); } using (System.IO.FileStream fs = System.IO.File.Create(filename)) { System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); writer.Write(content); writer.Close(); fs.Close(); } return(true); } catch { return(false); } }
public void SetDataOld(List <ResourceLocationData> locations, List <string> labels) { var tmpEntries = new List <Entry>(locations.Count); var providers = new List <string>(10); var providerIndices = new Dictionary <string, int>(10); var countEstimate = locations.Count * 2 + labels.Count; var internalIdToEntryIndex = new Dictionary <string, int>(countEstimate); var internalIdList = new List <string>(countEstimate); List <object> keys = new List <object>(countEstimate); var keyToIndex = new Dictionary <object, int>(countEstimate); var tmpBuckets = new Dictionary <int, List <int> >(countEstimate); for (int i = 0; i < locations.Count; i++) { var rld = locations[i]; int providerIndex = 0; if (!providerIndices.TryGetValue(rld.m_provider, out providerIndex)) { providerIndices.Add(rld.m_provider, providerIndex = providers.Count); providers.Add(rld.m_provider); } int internalIdIndex = 0; if (!internalIdToEntryIndex.TryGetValue(rld.m_internalId, out internalIdIndex)) { internalIdToEntryIndex.Add(rld.m_internalId, internalIdIndex = internalIdList.Count); internalIdList.Add(rld.m_internalId); } var e = new Entry() { internalId = internalIdIndex, providerIndex = (byte)providerIndex, dependency = -1 }; if (rld.m_type == ResourceLocationData.LocationType.Int) { AddToBucket(tmpBuckets, keyToIndex, keys, int.Parse(rld.m_address), tmpEntries.Count, 1); } else if (rld.m_type == ResourceLocationData.LocationType.String) { AddToBucket(tmpBuckets, keyToIndex, keys, rld.m_address, tmpEntries.Count, 1); } if (!string.IsNullOrEmpty(rld.m_guid)) { AddToBucket(tmpBuckets, keyToIndex, keys, Hash128.Parse(rld.m_guid), tmpEntries.Count, 1); } if (rld.m_labelMask != 0) { for (int t = 0; t < labels.Count; t++) { if ((rld.m_labelMask & (1 << t)) != 0) { AddToBucket(tmpBuckets, keyToIndex, keys, labels[t], tmpEntries.Count, 100); } } } tmpEntries.Add(e); } for (int i = 0; i < locations.Count; i++) { var rld = locations[i]; int dependency = -1; if (rld.m_dependencies != null && rld.m_dependencies.Length > 0) { if (rld.m_dependencies.Length == 1) { dependency = keyToIndex[rld.m_dependencies[0]]; } else { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (var d in rld.m_dependencies) { sb.Append(d); } var key = sb.ToString().GetHashCode(); int keyIndex = -1; foreach (var d in rld.m_dependencies) { var ki = keyToIndex[d]; var depBucket = tmpBuckets[ki]; keyIndex = AddToBucket(tmpBuckets, keyToIndex, keys, key, depBucket[0], 10); } dependency = keyIndex; } var e = tmpEntries[i]; e.dependency = dependency; tmpEntries[i] = e; } } m_internalIds = internalIdList.ToArray(); m_providerIds = providers.ToArray(); var entryData = new byte[tmpEntries.Count * 4 * 3 + 4]; var offset = Serialize(entryData, tmpEntries.Count, 0); for (int i = 0; i < tmpEntries.Count; i++) { var e = tmpEntries[i]; offset = Serialize(entryData, e.internalId, offset); offset = Serialize(entryData, e.providerIndex, offset); offset = Serialize(entryData, e.dependency, offset); } m_entryDataString = Convert.ToBase64String(entryData); int bucketEntryCount = 0; var bucketList = new List <Bucket>(keys.Count); for (int i = 0; i < keys.Count; i++) { var bucketIndex = keyToIndex[keys[i]]; List <int> entries = tmpBuckets[bucketIndex]; bucketList.Add(new Bucket() { entries = entries.ToArray() }); bucketEntryCount += entries.Count; } var keyData = new List <byte>(bucketList.Count * 10); keyData.AddRange(BitConverter.GetBytes(bucketList.Count)); int dataOffset = 4; for (int i = 0; i < bucketList.Count; i++) { var bucket = bucketList[i]; bucket.dataOffset = dataOffset; bucketList[i] = bucket; var key = keys[i]; var kt = key.GetType(); if (kt == typeof(string)) { string str = key as string; byte[] tmp = System.Text.Encoding.Unicode.GetBytes(str); byte[] tmp2 = System.Text.Encoding.ASCII.GetBytes(str); if (System.Text.Encoding.Unicode.GetString(tmp) == System.Text.Encoding.ASCII.GetString(tmp2)) { keyData.Add((byte)KeyType.ASCIIString); keyData.AddRange(tmp2); dataOffset += tmp2.Length + 1; } else { keyData.Add((byte)KeyType.UnicodeString); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } } else if (kt == typeof(UInt32)) { byte[] tmp = BitConverter.GetBytes((UInt32)key); keyData.Add((byte)KeyType.UInt32); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(UInt16)) { byte[] tmp = BitConverter.GetBytes((UInt16)key); keyData.Add((byte)KeyType.UInt16); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(Int32)) { byte[] tmp = BitConverter.GetBytes((Int32)key); keyData.Add((byte)KeyType.Int32); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(int)) { byte[] tmp = BitConverter.GetBytes((UInt32)key); keyData.Add((byte)KeyType.UInt32); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(Hash128)) { var guid = (Hash128)key; byte[] tmp = System.Text.Encoding.ASCII.GetBytes(guid.ToString()); keyData.Add((byte)KeyType.Hash128); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } } m_keyDataString = Convert.ToBase64String(keyData.ToArray()); var bucketData = new byte[4 + bucketList.Count * 8 + bucketEntryCount * 4]; offset = Serialize(bucketData, bucketList.Count, 0); for (int i = 0; i < bucketList.Count; i++) { offset = Serialize(bucketData, bucketList[i].dataOffset, offset); offset = Serialize(bucketData, bucketList[i].entries.Length, offset); foreach (var e in bucketList[i].entries) { offset = Serialize(bucketData, e, offset); } } m_bucketDataString = Convert.ToBase64String(bucketData); #if SERIALIZE_CATALOG_AS_BINARY //TODO: investigate saving catalog as binary - roughly 20% size decrease, still needs a provider implementation var stream = new System.IO.MemoryStream(); var bw = new System.IO.BinaryWriter(stream); foreach (var i in m_internalIds) { bw.Write(i); } foreach (var p in m_providerIds) { bw.Write(p); } bw.Write(entryData); bw.Write(keyData.ToArray()); bw.Write(bucketData); bw.Flush(); bw.Close(); stream.Flush(); System.IO.File.WriteAllBytes("Library/catalog_binary.bytes", stream.ToArray()); System.IO.File.WriteAllText("Library/catalog_binary.txt", Convert.ToBase64String(stream.ToArray())); stream.Close(); #endif }
public static void OnCommand(byte[] bytes) { using (MemoryStream stream = new MemoryStream(bytes)) { using (BinaryReader r = new BinaryReader(stream)) { int cmdIndex = r.ReadInt32(); if (cmdIndex == 1) //previousely AB { if (GameSetup.IsMpServer && ModSettings.DifficultyChoosen) { using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(2); w.Write((int)ModSettings.difficulty); w.Write(ModSettings.FriendlyFire); w.Write((int)ModSettings.dropsOnDeath); w.Write(ModSettings.killOnDowned); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Clients); answerStream.Close(); } } } else if (cmdIndex == 2) //request for the what is the difficulty { if (!GameSetup.IsMpClient || ModSettings.IsDedicated) { return; } int index = r.ReadInt32(); ModSettings.FriendlyFire = r.ReadBoolean(); ModSettings.dropsOnDeath = (ModSettings.DropsOnDeathMode)r.ReadInt32(); ModSettings.killOnDowned = r.ReadBoolean(); Array values = Enum.GetValues(typeof(ModSettings.Difficulty)); ModSettings.difficulty = (ModSettings.Difficulty)values.GetValue(index); if (!ModSettings.DifficultyChoosen) { LocalPlayer.FpCharacter.UnLockView(); LocalPlayer.FpCharacter.MovementLocked = false; } ModSettings.DifficultyChoosen = true; } else if (cmdIndex == 3) //spell casted { int spellid = r.ReadInt32(); if (spellid == 1) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); BlackHole.CreateBlackHole(pos, r.ReadBoolean(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadString()); } else if (spellid == 2) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); HealingDome.CreateHealingDome(pos, r.ReadSingle(), r.ReadSingle(), r.ReadBoolean(), r.ReadBoolean(), r.ReadSingle()); } else if (spellid == 3) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); DarkBeam.Create(pos, r.ReadBoolean(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); } else if (spellid == 4) { bool isOn = r.ReadBoolean(); string packed = r.ReadString(); BlackFlame.ToggleOtherPlayer(packed, isOn); } else if (spellid == 5) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float radius = r.ReadSingle(); float speed = r.ReadSingle(); float dmg = r.ReadSingle(); bool GiveDmg = r.ReadBoolean(); bool GiveAr = r.ReadBoolean(); int ar = 0; if (GiveAr) { ar = r.ReadInt32(); } WarCry.Cast(pos, radius, speed, dmg, GiveDmg, GiveAr, ar); } else if (spellid == 6) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float duration = r.ReadSingle(); int id = r.ReadInt32(); Portal.CreatePortal(pos, duration, id, r.ReadBoolean(), r.ReadBoolean()); } else if (spellid == 7) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); Vector3 dir = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float dmg = r.ReadSingle(); string caster = r.ReadString(); float duration = r.ReadSingle(); bool slow = r.ReadBoolean(); bool dmgdebuff = r.ReadBoolean(); if (GameSetup.IsMpServer) { MagicArrow.Create(pos, dir, dmg, caster, duration, slow, dmgdebuff); } else { MagicArrow.CreateEffect(pos, dir, dmgdebuff, duration); } } else if (spellid == 8) { Purge.Cast(new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle(), r.ReadBoolean(), r.ReadBoolean()); } else if (spellid == 9) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float dist = r.ReadSingle(); SnapFreeze.CreateEffect(pos, dist); if (!GameSetup.IsMpClient) { SnapFreeze.HostAction(pos, dist, r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); } } else if (spellid == 10) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); Vector3 speed = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float dmg = r.ReadSingle(); uint id = r.ReadUInt32(); if (BallLightning.lastID < id) { BallLightning.lastID = id; } BallLightning.Create(pos, speed, dmg, id); } else if (spellid == 11) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float radius = r.ReadSingle(); float dmg = r.ReadSingle(); float duration = r.ReadSingle(); bool isArcane = r.ReadBoolean(); bool fromEnemy = r.ReadBoolean(); Cataclysm.Create(pos, radius, dmg, duration, isArcane ? Cataclysm.TornadoType.Arcane : Cataclysm.TornadoType.Fire, fromEnemy); } else if (spellid == 12) { //a request from a client to a host to spawn a ball lightning. The host assigns the id of //a ball lightning to not create overlapping ids using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(3); w.Write(10); w.Write(r.ReadSingle()); w.Write(r.ReadSingle()); w.Write(r.ReadSingle()); w.Write(r.ReadSingle()); w.Write(r.ReadSingle()); w.Write(r.ReadSingle()); w.Write(r.ReadSingle()); w.Write((uint)(BallLightning.lastID + 1)); w.Close(); BallLightning.lastID++; } ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone); answerStream.Close(); } } else if (spellid == 13) //parry was casted by a client { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float radius = r.ReadSingle(); bool ignite = r.ReadBoolean(); float dmg = r.ReadSingle(); DamageMath.DamageClamp(dmg, out int d, out int rep); var hits = Physics.SphereCastAll(pos, radius, Vector3.one); for (int i = 0; i < hits.Length; i++) { if (hits[i].transform.CompareTag("enemyCollide")) { for (int a = 0; a < rep; a++) { hits[i].transform.SendMessageUpwards("Hit", d, SendMessageOptions.DontRequireReceiver); if (ignite) { hits[i].transform.SendMessageUpwards("Burn", SendMessageOptions.DontRequireReceiver); } } } } } } else if (cmdIndex == 4) //remove item { PickUpManager.RemovePickup(r.ReadUInt64()); } else if (cmdIndex == 5) //create item { Item item = new Item(ItemDataBase.ItemBases[r.ReadInt32()], 1, 0, false); //reading first value, id ulong id = r.ReadUInt64(); item.level = r.ReadInt32(); int amount = r.ReadInt32(); Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); while (r.BaseStream.Position != r.BaseStream.Length) { ItemStat stat = new ItemStat(ItemDataBase.Stats[r.ReadInt32()]) { Amount = r.ReadSingle() }; item.Stats.Add(stat); } PickUpManager.SpawnPickUp(item, pos, amount, id); } else if (cmdIndex == 6) //host has been asked to share info on enemy { if (!GameSetup.IsMpClient) { ulong packed = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(packed)) { EnemyProgression ep = EnemyManager.hostDictionary[packed]; using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(7); w.Write(packed); w.Write(ep.EnemyName); w.Write(ep.Level); w.Write(ep._hp + ep._Health.Health); w.Write(ep.MaxHealth); w.Write(ep.bounty); w.Write(ep.Armor); w.Write(ep.ArmorReduction); w.Write(ep.Steadfast); w.Write(ep.abilities.Count); foreach (EnemyProgression.Abilities item in ep.abilities) { w.Write((int)item); } w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Clients); answerStream.Close(); } } else { CotfUtils.Log("no enemy in host's dictionary"); } } } else if (cmdIndex == 7) //host answered info about a enemy and the info is processed { if (ModSettings.IsDedicated) { return; } if (GameSetup.IsMpClient) { ulong packed = r.ReadUInt64(); if (!EnemyManager.allboltEntities.ContainsKey(packed)) { EnemyManager.GetAllEntities(); } if (EnemyManager.allboltEntities.ContainsKey(packed)) { BoltEntity entity = EnemyManager.allboltEntities[packed]; string name = r.ReadString(); int level = r.ReadInt32(); float health = r.ReadSingle(); float maxhealth = r.ReadSingle(); long bounty = r.ReadInt64(); int armor = r.ReadInt32(); int armorReduction = r.ReadInt32(); float steadfast = r.ReadSingle(); int length = r.ReadInt32(); int[] affixes = new int[length]; for (int i = 0; i < length; i++) { affixes[i] = r.ReadInt32(); } if (EnemyManager.clinetProgressions.ContainsKey(entity)) { ClinetEnemyProgression cp = EnemyManager.clinetProgressions[entity]; cp.creationTime = Time.time; cp.Entity = entity; cp.Level = level; cp.Health = health; cp.MaxHealth = maxhealth; cp.Armor = armor; cp.ArmorReduction = armorReduction; cp.EnemyName = name; cp.ExpBounty = bounty; cp.Steadfast = steadfast; cp.Affixes = affixes; } else { new ClinetEnemyProgression(entity, name, level, health, maxhealth, bounty, armor, armorReduction, steadfast, affixes); } } } } else if (cmdIndex == 8) //enemy spell casted { int id = r.ReadInt32(); if (id == 1) //snow aura { ulong packed = r.ReadUInt64(); SnowAura sa = new GameObject("Snow").AddComponent <SnowAura>(); if (!EnemyManager.allboltEntities.ContainsKey(packed)) { EnemyManager.GetAllEntities(); } sa.followTarget = EnemyManager.allboltEntities[packed].transform; } else if (id == 2) //fire aura { ulong packed = r.ReadUInt64(); float dmg = r.ReadSingle(); GameObject go = EnemyManager.allboltEntities[packed].gameObject; FireAura.Cast(go, dmg); } } else if (cmdIndex == 9) //poison Player { string playerID = r.ReadString(); if (ModReferences.ThisPlayerID == playerID) { int source = r.ReadInt32(); float amount = r.ReadSingle(); float duration = r.ReadSingle(); BuffDB.AddBuff(3, source, amount, duration); } } else if (cmdIndex == 10) //kill experience { ModdedPlayer.instance.AddKillExperience(r.ReadInt64()); } else if (cmdIndex == 11) //add experience without massacre { ModdedPlayer.instance.AddFinalExperience(r.ReadInt64()); } else if (cmdIndex == 12) //root the player { if (ModdedPlayer.instance.RootImmune == 0 && ModdedPlayer.instance.StunImmune == 0) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); if ((LocalPlayer.Transform.position - pos).sqrMagnitude < 1250) { float duration = r.ReadSingle(); ModdedPlayer.instance.Root(duration); using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(14); w.Write(LocalPlayer.Transform.position.x); w.Write(LocalPlayer.Transform.position.y); w.Write(LocalPlayer.Transform.position.z); w.Write(duration); w.Close(); } NetworkManager.SendLine(answerStream.ToArray(), NetworkManager.Target.Everyone); answerStream.Close(); } } } } else if (cmdIndex == 13) //stun the player { if (ModSettings.IsDedicated) { return; } if (ModdedPlayer.instance.StunImmune == 0) { string playerID = r.ReadString(); if (ModReferences.ThisPlayerID == playerID) { float duration = r.ReadSingle(); ModdedPlayer.instance.Stun(duration); } } } else if (cmdIndex == 14) //player has been chained, now spawn effect { if (ModSettings.IsDedicated) { return; } Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float duration = r.ReadSingle(); RootSpell.Create(pos, duration); } else if (cmdIndex == 15) //create trap sphere { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float duration = r.ReadSingle(); float radius = r.ReadSingle(); TrapSphereSpell.Create(pos, radius, duration); } else if (cmdIndex == 16) //create enemy laser, aka plasma cannon { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); Vector3 dir = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); EnemyLaser.CreateLaser(pos, dir); } else if (cmdIndex == 17) //create enemy meteor rain { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); Meteor.CreateEnemy(pos, r.ReadInt32()); } else if (cmdIndex == 18) //player's level info, or command to wipe level data { if (r.BaseStream.Position == r.BaseStream.Length) { ModReferences.PlayerLevels.Clear(); } using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(19); w.Write(ModReferences.ThisPlayerID); w.Write(ModdedPlayer.instance.Level); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), NetworkManager.Target.Others); answerStream.Close(); } } else if (cmdIndex == 19)//add or update some players level to list { string packed = r.ReadString(); int level = r.ReadInt32(); if (ModReferences.PlayerLevels.ContainsKey(packed)) { ModReferences.PlayerLevels[packed] = level; } else { ModReferences.PlayerLevels.Add(packed, level); } } else if (cmdIndex == 20) //enemy hitmarker { if (ModSettings.IsDedicated) { return; } int amount = r.ReadInt32(); Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); Color c = new Color(r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); MainMenu.CreateHitMarker(amount, pos, c); } else if (cmdIndex == 21) //player hitmarker { if (ModSettings.IsDedicated) { return; } int amount = r.ReadInt32(); Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); new MainMenu.HitMarker(amount, pos, true); } else if (cmdIndex == 22) //slow Enemy { if (GameSetup.IsMpServer || GameSetup.IsSinglePlayer) { ulong id = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(id)) { float amount = r.ReadSingle(); float time = r.ReadSingle(); int src = r.ReadInt32(); EnemyManager.hostDictionary[id].Slow(src, amount, time); } } } else if (cmdIndex == 23) //sync magic find { if (GameSetup.IsMpServer) { if (ModSettings.IsDedicated) { ItemDataBase.MagicFind = 1; } else { ItemDataBase.MagicFind = ModdedPlayer.instance.MagicFindMultipier; } } else { using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(24); w.Write(ModdedPlayer.instance.MagicFindMultipier); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.OnlyServer); answerStream.Close(); } } } else if (cmdIndex == 24) //update magic find for host { if (GameSetup.IsMpServer) { ItemDataBase.MagicFind *= r.ReadSingle(); } } else if (cmdIndex == 25) //ask for item { if (GameSetup.IsMpServer) { ulong itemID = r.ReadUInt64(); if (PickUpManager.PickUps.ContainsKey(itemID)) { int itemAmount = r.ReadInt32(); string playerID = r.ReadString(); if (PickUpManager.PickUps[itemID].amount > 0) { int givenAmount = itemAmount; if (itemAmount > PickUpManager.PickUps[itemID].amount) { givenAmount = Mathf.Min(PickUpManager.PickUps[itemID].amount, itemAmount); } NetworkManager.SendItemToPlayer(PickUpManager.PickUps[itemID].item, playerID, givenAmount); PickUpManager.PickUps[itemID].amount -= givenAmount; if (PickUpManager.PickUps[itemID].amount > 0) { return; } } } using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(4); w.Write(itemID); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Clients); answerStream.Close(); } } } else if (cmdIndex == 26) //give item to player { string playerID = r.ReadString(); if (ModReferences.ThisPlayerID == playerID) { //creating the item. Item item = new Item(ItemDataBase.ItemBases[r.ReadInt32()], r.ReadInt32(), 0, false) { level = r.ReadInt32() }; //adding stats to the item while (r.BaseStream.Position != r.BaseStream.Length) { ItemStat stat = new ItemStat(ItemDataBase.Stats[r.ReadInt32()]) { Amount = r.ReadSingle() }; item.Stats.Add(stat); } Player.Inventory.Instance.AddItem(item, item.Amount); } } else if (cmdIndex == 27) // bonus fire damage { if (GameSetup.IsMpServer || GameSetup.IsSinglePlayer) { ulong id = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(id)) { float amount = r.ReadSingle(); float time = r.ReadSingle(); int src = r.ReadInt32(); EnemyManager.hostDictionary[id].FireDebuff(src, amount, time); } } } else if (cmdIndex == 28) //custom weapon in mp { string id = r.ReadString(); int weaponID = r.ReadInt32(); if (!ModReferences.PlayerHands.ContainsKey(id)) { ModReferences.FindHands(); } if (ModReferences.PlayerHands.ContainsKey(id)) { CoopCustomWeapons.SetWeaponOn(ModReferences.PlayerHands[id], weaponID); Console.WriteLine(ModReferences.PlayerHands[id].name); } else { Debug.LogWarning("NO HAND IN COMMAND READER"); } } else if (cmdIndex == 29) //request for enemy damage information { if (GameSetup.IsMpServer) { ulong id = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(id)) { EnemyProgression p = EnemyManager.hostDictionary[id]; using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(30); w.Write(id); w.Write(p.BaseDamageMult); foreach (EnemyProgression.Abilities ability in p.abilities) { w.Write((int)ability); } w.Close(); } NetworkManager.SendLine(answerStream.ToArray(), NetworkManager.Target.Clients); answerStream.Close(); } } } } else if (cmdIndex == 30) //answer to client damage { ulong id = r.ReadUInt64(); float dmg = r.ReadSingle(); List <EnemyProgression.Abilities> abilities = new List <EnemyProgression.Abilities>(); while (r.BaseStream.Position != r.BaseStream.Length) { abilities.Add((EnemyProgression.Abilities)r.ReadInt32()); } new ClientEnemy(id, dmg, abilities); } else if (cmdIndex == 31) //detonate ball lightning { uint id = r.ReadUInt32(); Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); if (BallLightning.list.ContainsKey(id)) { BallLightning.list[id].CoopTrigger(pos); } } else if (cmdIndex == 32) //apply DoT to an enemy { ulong id = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(id)) { EnemyProgression p = EnemyManager.hostDictionary[id]; p.DoDoT(r.ReadInt32(), r.ReadSingle()); } } else if (cmdIndex == 33) //enemy got bashed { ulong enemy = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(enemy)) { EnemyProgression p = EnemyManager.hostDictionary[enemy]; float duration = r.ReadSingle(); var source = r.ReadInt32(); float slowAmount = r.ReadSingle(); float dmgDebuff = r.ReadSingle(); var bleedDmg = r.ReadInt32(); float bleedChance = r.ReadSingle(); p.Slow(source, slowAmount, duration); p.DmgTakenDebuff(source, dmgDebuff, duration); if (UnityEngine.Random.value < bleedChance) { p.DoDoT(bleedDmg, duration); } } } else if (cmdIndex == 34) { if (GameSetup.IsMpServer) { ulong enemy = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(enemy)) { EnemyProgression p = EnemyManager.hostDictionary[enemy]; var source = r.ReadInt32(); float amount = r.ReadSingle(); float duration = r.ReadSingle(); p.DmgTakenDebuff(source, amount, duration); } } } else if (cmdIndex == 35) //clear ping command { string player = r.ReadString(); if (MainMenu.Instance.otherPlayerPings.ContainsKey(player)) { MainMenu.Instance.otherPlayerPings.Remove(player); } } else if (cmdIndex == 36) //create ping command { string PlayerID = r.ReadString(); MarkObject.PingType ptype = (MarkObject.PingType)r.ReadInt32(); switch (ptype) { case MarkObject.PingType.Enemy: ulong EnemyID = r.ReadUInt64(); if (!EnemyManager.allboltEntities.ContainsKey(EnemyID)) { EnemyManager.GetAllEntities(); } if (EnemyManager.allboltEntities.ContainsKey(EnemyID)) { bool isElite = r.ReadBoolean(); string name = r.ReadString(); Transform tr = EnemyManager.allboltEntities[EnemyID].transform; if (PlayerID == ModReferences.ThisPlayerID) { MainMenu.Instance.localPlayerPing = new MarkEnemy(tr, name, isElite); } else { if (MainMenu.Instance.otherPlayerPings.ContainsKey(PlayerID)) { MainMenu.Instance.otherPlayerPings[PlayerID] = new MarkEnemy(tr, name, isElite); } else { MainMenu.Instance.otherPlayerPings.Add(PlayerID, new MarkEnemy(tr, name, isElite)); } } } break; case MarkObject.PingType.Location: float x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle(); if (PlayerID == ModReferences.ThisPlayerID) { MainMenu.Instance.localPlayerPing = new MarkPostion(new Vector3(x, y, z)); } else { if (MainMenu.Instance.otherPlayerPings.ContainsKey(PlayerID)) { MainMenu.Instance.otherPlayerPings[PlayerID] = new MarkPostion(new Vector3(x, y, z)); } else { MainMenu.Instance.otherPlayerPings.Add(PlayerID, new MarkPostion(new Vector3(x, y, z))); } } break; case MarkObject.PingType.Item: ulong PickupID = r.ReadUInt64(); if (PickUpManager.PickUps.ContainsKey(PickupID)) { var pu = PickUpManager.PickUps[PickupID]; if (PlayerID == ModReferences.ThisPlayerID) { MainMenu.Instance.localPlayerPing = new MarkPickup(pu.transform, pu.item.name, pu.item.Rarity); } else { if (MainMenu.Instance.otherPlayerPings.ContainsKey(PlayerID)) { MainMenu.Instance.otherPlayerPings[PlayerID] = new MarkPickup(pu.transform, pu.item.name, pu.item.Rarity); } else { MainMenu.Instance.otherPlayerPings.Add(PlayerID, new MarkPickup(pu.transform, pu.item.name, pu.item.Rarity)); } } } break; } } else if (cmdIndex == 37) //create ping for enemy { if (GameSetup.IsMpServer) { string PlayerID = r.ReadString(); ulong EnemyID = r.ReadUInt64(); if (EnemyManager.hostDictionary.ContainsKey(EnemyID)) { var enemy = EnemyManager.hostDictionary[EnemyID]; using (MemoryStream answerStream = new MemoryStream()) { using (BinaryWriter w = new BinaryWriter(answerStream)) { w.Write(36); w.Write(PlayerID); w.Write(0); w.Write(EnemyID); w.Write(enemy._rarity != EnemyProgression.EnemyRarity.Normal); w.Write(enemy.EnemyName); w.Close(); } NetworkManager.SendLine(answerStream.ToArray(), NetworkManager.Target.Everyone); answerStream.Close(); } } } } else if (cmdIndex == 38) //spark of light after darkness callback to clients { if (GameSetup.IsMpClient) { string PlayerID = r.ReadString(); if (ModReferences.ThisPlayerID == PlayerID) { Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); SpellActions.CastBallLightning(pos, Vector3.down); } } } else if (cmdIndex == 39) //archangel bow hit a player { var s = r.ReadString(); if (ModReferences.ThisPlayerID == s) { BuffDB.AddBuff(25, 91, r.ReadSingle(), 30); BuffDB.AddBuff(9, 92, 1.35f, 30); ModdedPlayer.instance.damageAbsorbAmounts[2] = r.ReadSingle(); } } else if (cmdIndex == 40) //buff a player by ID { var s = r.ReadString(); if (ModReferences.ThisPlayerID == s) { BuffDB.AddBuff(r.ReadInt32(), r.ReadInt32(), r.ReadSingle(), r.ReadSingle()); } } else if (cmdIndex == 41) //buff a player by distance { var vector = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); var dist = r.ReadSingle(); if ((vector - LocalPlayer.Transform.position).sqrMagnitude <= dist * dist) { BuffDB.AddBuff(r.ReadInt32(), r.ReadInt32(), r.ReadSingle(), r.ReadSingle()); } } else if (cmdIndex == 42) //buff all players globally { BuffDB.AddBuff(r.ReadInt32(), r.ReadInt32(), r.ReadSingle(), r.ReadSingle()); } r.Close(); } stream.Close(); } }
private void button3_Click(object sender, EventArgs e) // Save Current { if (tabControl1.SelectedIndex == 0 && listBox1.SelectedIndex != -1) { System.IO.BinaryWriter writeEvent = new System.IO.BinaryWriter(File.OpenWrite(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); writeEvent.BaseStream.Position = 0x4 + 0x14 * listBox1.SelectedIndex; writeEvent.Write((Int16)numericUpDown1.Value); writeEvent.Write((Int16)numericUpDown2.Value); writeEvent.Write((Int16)numericUpDown3.Value); writeEvent.Write((Int16)numericUpDown4.Value); writeEvent.Write((Int16)numericUpDown5.Value); writeEvent.Write((Int16)numericUpDown10.Value); writeEvent.Write((Int16)numericUpDown9.Value); writeEvent.Write((Int16)numericUpDown8.Value); writeEvent.Write((Int16)numericUpDown7.Value); writeEvent.Write((Int16)numericUpDown6.Value); writeEvent.Close(); } if (tabControl1.SelectedIndex == 1 && listBox2.SelectedIndex != -1) { System.IO.BinaryWriter writeEvent = new System.IO.BinaryWriter(File.OpenWrite(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); writeEvent.BaseStream.Position = 0x8 + 0x14 * furnitureCount + 0x20 * listBox2.SelectedIndex; writeEvent.Write((Int16)numericUpDown34.Value); writeEvent.Write((Int16)numericUpDown33.Value); writeEvent.Write((Int16)numericUpDown32.Value); writeEvent.Write((Int16)numericUpDown31.Value); writeEvent.Write((Int16)numericUpDown30.Value); writeEvent.Write((Int16)numericUpDown36.Value); writeEvent.Write((Int16)numericUpDown38.Value); writeEvent.Write((Int16)numericUpDown40.Value); writeEvent.Write((Int16)numericUpDown29.Value); writeEvent.Write((Int16)numericUpDown28.Value); writeEvent.Write((Int16)numericUpDown27.Value); writeEvent.Write((Int16)numericUpDown26.Value); writeEvent.Write((Int16)numericUpDown25.Value); writeEvent.Write((Int16)numericUpDown35.Value); writeEvent.Write((Int16)numericUpDown37.Value); writeEvent.Write((Int16)numericUpDown38.Value); writeEvent.Close(); } if (tabControl1.SelectedIndex == 2 && listBox3.SelectedIndex != -1) { System.IO.BinaryWriter writeEvent = new System.IO.BinaryWriter(File.OpenWrite(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); writeEvent.BaseStream.Position = 0xc + 0x14 * furnitureCount + 0x20 * overworldCount + 0xc * listBox3.SelectedIndex; writeEvent.Write((Int16)numericUpDown16.Value); writeEvent.Write((Int16)numericUpDown15.Value); writeEvent.Write((Int16)numericUpDown14.Value); writeEvent.Write((Int16)(numericUpDown13.Value - 1)); writeEvent.Write((Int16)numericUpDown12.Value); writeEvent.Write((Int16)numericUpDown11.Value); writeEvent.Close(); } if (tabControl1.SelectedIndex == 3 && listBox4.SelectedIndex != -1) { System.IO.BinaryWriter writeEvent = new System.IO.BinaryWriter(File.OpenWrite(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); writeEvent.BaseStream.Position = 0x10 + 0x14 * furnitureCount + 0x20 * overworldCount + 0xc * warpCount + 0x10 * listBox4.SelectedIndex; writeEvent.Write((Int16)numericUpDown24.Value); writeEvent.Write((Int16)numericUpDown18.Value); writeEvent.Write((Int16)numericUpDown21.Value); writeEvent.Write((Int16)numericUpDown23.Value); writeEvent.Write((Int16)numericUpDown20.Value); writeEvent.Write((Int16)numericUpDown17.Value); writeEvent.Write((Int16)numericUpDown19.Value); writeEvent.Write((Int16)numericUpDown22.Value); writeEvent.Close(); } }
private void BytesDecodeTest(CS2CPrtcData p) { if (p == null || p.Type != 10531) { return; } const int count = 10000; Single totalTime = 0; IntPtr L = LuaScriptMgr.Instance.GetL(); if (L != IntPtr.Zero) { var startTime = DateTime.Now; for (int i = 0; i < count; i++) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getglobal(L, "ProcessMoveProtocol2"); if (!LuaDLL.lua_isnil(L, -1)) { LuaDLL.lua_pushinteger(L, p.Type); LuaDLL.lua_pushlstring(L, p.Buffer, p.Buffer.Length); LuaDLL.lua_pushboolean(L, false); LuaDLL.lua_pushboolean(L, false); if (LuaDLL.lua_pcall(L, 4, 0, 0) != 0) { HobaDebuger.LogLuaError(LuaDLL.lua_tostring(L, -1)); } } LuaDLL.lua_settop(L, oldTop); } totalTime = (DateTime.Now - startTime).Ticks; } UnityEngine.Debug.LogErrorFormat("ProcessMovePBProtocol * {0} = {1} ticks", count, totalTime); byte[] inputBytes = new byte[100]; System.IO.MemoryStream ms = new System.IO.MemoryStream(inputBytes); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms); { //entityid bw.Write(2); //CurrentPosition bw.Write(1.0f); bw.Write(2.0f); bw.Write(3.0f); //CurrentOrientation bw.Write(4.0f); bw.Write(5.0f); bw.Write(6.0f); //MoveType bw.Write(3); //MoveDirection bw.Write(7.0f); bw.Write(8.0f); bw.Write(9.0f); //MoveSpeed bw.Write(10.0f); //TimeInterval bw.Write(4); //DstPosition bw.Write(11.0f); bw.Write(12.0f); bw.Write(33.0f); //IsDestPosition bw.Write(false); ms.Seek(0, System.IO.SeekOrigin.Begin); } System.IO.BinaryReader br = new System.IO.BinaryReader(ms); { var startTime = DateTime.Now; for (int i = 0; i < count; i++) { br.BaseStream.Position = 0; var EntityId = br.ReadInt32(); var vecX = br.ReadSingle(); var vecY = br.ReadSingle(); var vecZ = br.ReadSingle(); var CurrentPosition = new UnityEngine.Vector3(vecX, vecY, vecZ); vecX = br.ReadSingle(); vecY = br.ReadSingle(); vecZ = br.ReadSingle(); var CurrentOrientation = new UnityEngine.Vector3(vecX, vecY, vecZ); var MoveType = br.ReadInt32(); vecX = br.ReadSingle(); vecY = br.ReadSingle(); vecZ = br.ReadSingle(); var MoveDirection = new UnityEngine.Vector3(vecX, vecY, vecZ); var MoveSpeed = br.ReadSingle(); var TimeInterval = br.ReadInt32(); vecX = br.ReadSingle(); vecY = br.ReadSingle(); vecZ = br.ReadSingle(); var DstPosition = new UnityEngine.Vector3(vecX, vecY, vecZ); var IsDestPosition = br.ReadBoolean(); if (L != IntPtr.Zero) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getglobal(L, "ProcessMoveProtocol1"); if (!LuaDLL.lua_isnil(L, -1)) { LuaScriptMgr.Push(L, EntityId); LuaScriptMgr.Push(L, CurrentPosition); LuaScriptMgr.Push(L, CurrentOrientation); LuaScriptMgr.Push(L, MoveType); LuaScriptMgr.Push(L, MoveDirection); LuaScriptMgr.Push(L, MoveSpeed); LuaScriptMgr.Push(L, TimeInterval); LuaScriptMgr.Push(L, DstPosition); LuaScriptMgr.Push(L, IsDestPosition); if (LuaDLL.lua_pcall(L, 9, 0, 0) != 0) { HobaDebuger.LogLuaError(LuaDLL.lua_tostring(L, -1)); } } LuaDLL.lua_settop(L, oldTop); } } totalTime = (DateTime.Now - startTime).Ticks; } bw.Close(); br.Close(); ms.Close(); ms.Dispose(); UnityEngine.Debug.LogErrorFormat("ProcessMoveProtocol * {0} = {1} ticks", count, totalTime); }
public static void Write <T>(string fileName, List <T> values, List <Func <T, object> > mapping, List <DbfFieldDescriptor> columns, Encoding encoding) { int control = 0; try { if (columns.Count != mapping.Count) { throw new NotImplementedException(); } System.IO.Stream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Create); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); DbfHeader header = new DbfHeader(values.Count, mapping.Count, GetRecordLength(columns), encoding); writer.Write(IRI.Ket.IO.BinaryStream.StructureToByteArray(header)); foreach (var item in columns) { writer.Write(IRI.Ket.IO.BinaryStream.StructureToByteArray(item)); } //Terminator writer.Write(byte.Parse("0D", System.Globalization.NumberStyles.HexNumber)); for (int i = 0; i < values.Count; i++) { control = i; // All dbf field records begin with a deleted flag field. Deleted - 0x2A (asterisk) else 0x20 (space) writer.Write(byte.Parse("20", System.Globalization.NumberStyles.HexNumber)); for (int j = 0; j < mapping.Count; j++) { byte[] temp = new byte[columns[j].Length]; object value = mapping[j](values[i]); if (value != null) { encoding.GetBytes(value.ToString(), 0, value.ToString().Length, temp, 0); } string tt = encoding.GetString(temp); var le = tt.Length; writer.Write(temp); } } //End of file writer.Write(byte.Parse("1A", System.Globalization.NumberStyles.HexNumber)); writer.Close(); stream.Close(); System.IO.File.WriteAllText(GetCpgFileName(fileName), encoding.BodyName); } catch (Exception ex) { string message = ex.Message; string m2 = message + " " + control.ToString(); } }
private void f16_ButtonDecryptFile_Click(object sender, EventArgs e) { f16_labelPB.Text = "Проверка ключа..."; f16_labelPB.Update(); if (Key.Length != 8) { MessageBox.Show("Необходимо ввести ключ длиной 8 байт", "Ошибка"); f16_labelPB.Text = "Готов к работе"; f16_labelPB.Update(); goto exit_label; } CheckWeaknessOfKey(); progressBar.Value = 0; LinkedList <byte> File = new LinkedList <byte>(); f16_labelPB.Text = "Выбор файла..."; f16_labelPB.Update(); OpenFileDialog Load = new OpenFileDialog(); if (Load.ShowDialog() == DialogResult.OK) { f16_labelPB.Text = "Считываем из файла..."; f16_labelPB.Update(); System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default); while (reader.PeekChar() > -1) { File.AddLast(reader.ReadByte()); } reader.Close(); } else { f16_labelPB.Text = "Готов к работе"; f16_labelPB.Update(); return; } byte[] Ciphertext = File.ToArray(); File.Clear(); progressBar.Maximum = Ciphertext.Length / 8; f16_labelPB.Text = "Расшифровываем..."; f16_labelPB.Update(); byte[] DecryptText; Cryption(false, ref Ciphertext, out DecryptText); int count = 0; for (int i = DecryptText.Length - 1; i >= DecryptText.Length - 8; i--) { if (DecryptText[i] == 0x80) { count++; break; } if (DecryptText[i] == 0x00) { count++; continue; } } SaveFileDialog Save = new SaveFileDialog(); if (Save.ShowDialog() == DialogResult.OK) { f16_labelPB.Text = "Сохраняем результат в файл..."; f16_labelPB.Update(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(Save.FileName, System.IO.FileMode.OpenOrCreate), Encoding.Default); for (int i = 0; i < DecryptText.Length - count; i++) { writer.Write(DecryptText[i]); } writer.Close(); } else { f16_labelPB.Text = "Готов к работе"; f16_labelPB.Update(); return; } f16_labelPB.Text = "Готово."; f16_labelPB.Update(); exit_label :; }
static void CreateAtlas() { string path = Application.dataPath + "/htmlProject/_Data/Atlas/bmp0"; List <Texture2D> texList = new List <Texture2D>(); var files = (new System.IO.DirectoryInfo(path)).GetFiles(); foreach (var f in files) { if (f.Extension == ".psd" || f.Extension == ".jpg" || f.Extension == ".png" || f.Extension == ".gif") { string path2 = "Assets/htmlProject/_Data/Atlas/bmp0/" + f.Name; //Debug.Log("Load=" + path2); Texture2D tex = (Texture2D)Resources.LoadAssetAtPath(path2, typeof(Texture2D)); if (tex != null) { texList.Add((Texture2D)tex); Debug.Log("tex=" + path2); } } } var size = 4096; var tex2d = new Texture2D(size, size); var rectlist = tex2d.PackTextures(texList.ToArray(), 1, size); tex2d.name = "atlas0"; tex2d.Apply(); using (var fs = new System.IO.FileStream(Application.dataPath + "/htmlProject/_Data/Atlas/" + tex2d.name + ".png", System.IO.FileMode.Create)) { var bw = new System.IO.BinaryWriter(fs); bw.Write(tex2d.EncodeToPNG()); bw.Close(); fs.Close(); } GameObject prefab = (GameObject)Resources.LoadAssetAtPath("Assets/htmlProject/_Data/Atlas/" + tex2d.name + ".prefab", typeof(GameObject)); AssetDatabase.StartAssetEditing(); { hgAtlasInfo ab = prefab.GetComponent <hgAtlasInfo>(); hgAtlasInfoData ai = ab.m_data; List <hgAtlasInfoData.DATA> saveList = new List <hgAtlasInfoData.DATA>(); if (ai != null && ai.list != null) { foreach (var d in ai.list) { saveList.AddRange(ai.list); } } Func <string, hgAtlasInfoData.DATA> find = (nm) => { foreach (var d in saveList) { if (d.texname == nm) { return(d); } } return(null); }; List <hgAtlasInfoData.DATA> list = new List <hgAtlasInfoData.DATA>(); for (int i = 0; i < texList.Count; i++) { var t = texList[i]; var r = rectlist[i]; var old = find(t.name); var d = new hgAtlasInfoData.DATA(old); d.texname = t.name; d.rect = r; list.Add(d); } ai.list = list.ToArray(); ai.atlasName = tex2d.name; ai.width = tex2d.width; ai.height = tex2d.height; ab.m_data = ai; } AssetDatabase.StopAssetEditing(); EditorUtility.SetDirty(prefab); AssetDatabase.SaveAssets(); EditorUtility.DisplayDialog("INFO", "CREATED!", "OK"); }
private void btnActivation_Click(object sender, System.EventArgs e) { try { string cdkeyStr = this.textBox_CDkey.Text.ToString(); if (string.IsNullOrEmpty(cdkeyStr)) { MessageBox.Show("输入的激活码为空!", "提示", MessageBoxButtons.OK); } else if (cdkeyStr == "请输入20位激活码") { MessageBox.Show("输入的激活码为空!", "提示", MessageBoxButtons.OK); } else if (cdkeyStr.Length != 20) { MessageBox.Show("输入的激活码无效!", "提示", MessageBoxButtons.OK); } else { string yearStr = cdkeyStr.Substring(6, 4); string monthStr = cdkeyStr.Substring(10, 2); string dayStr = cdkeyStr.Substring(12, 2); string hourStr = cdkeyStr.Substring(14, 2); string minuteStr = cdkeyStr.Substring(16, 2); string secondStr = cdkeyStr.Substring(18, 2); int iYear = this.GetIntTimeNum(yearStr); int iMonth = this.GetIntTimeNum(monthStr); int iDay = this.GetIntTimeNum(dayStr); int iHour = this.GetIntTimeNum(hourStr); int iMinute = this.GetIntTimeNum(minuteStr); int iSecond = this.GetIntTimeNum(secondStr); if (iYear != 0 && iMonth != 0 && iDay != 0 && iHour < 24 && iMinute < 60 && iSecond < 60) { System.ValueType valueType = default(System.DateTime); (System.DateTime)valueType = new System.DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond); if (((System.DateTime)System.DateTime.Now).CompareTo(valueType) >= 0) { MessageBox.Show("激活码无效!", "提示", MessageBoxButtons.OK); this.bRegisterSuccFlag = false; } else { string chyStr = cdkeyStr.Substring(0, 6); if ("CCHHYY" == chyStr) { System.ValueType nTime = System.DateTime.Now; System.ValueType valueType2 = default(System.DateTime); (System.DateTime)valueType2 = new System.DateTime(((System.DateTime)nTime).Year, ((System.DateTime)nTime).Month, ((System.DateTime)nTime).Day + 3, ((System.DateTime)nTime).Hour, ((System.DateTime)nTime).Minute, ((System.DateTime)nTime).Second); this.endTime = valueType2; } else if ("CCYYHH" == chyStr) { System.ValueType nTime2 = System.DateTime.Now; System.ValueType valueType3 = default(System.DateTime); (System.DateTime)valueType3 = new System.DateTime(((System.DateTime)nTime2).Year, ((System.DateTime)nTime2).Month + 1, ((System.DateTime)nTime2).Day, ((System.DateTime)nTime2).Hour, ((System.DateTime)nTime2).Minute, ((System.DateTime)nTime2).Second); this.endTime = valueType3; } else if ("YYHHCC" == chyStr) { System.ValueType nTime3 = System.DateTime.Now; System.ValueType valueType4 = default(System.DateTime); (System.DateTime)valueType4 = new System.DateTime(((System.DateTime)nTime3).Year + 1, ((System.DateTime)nTime3).Month, ((System.DateTime)nTime3).Day, ((System.DateTime)nTime3).Hour, ((System.DateTime)nTime3).Minute, ((System.DateTime)nTime3).Second); this.endTime = valueType4; } else { System.ValueType valueType5 = default(System.DateTime); (System.DateTime)valueType5 = new System.DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond); this.endTime = valueType5; } try { System.IO.FileStream fs = new System.IO.FileStream(this.licFilePathStr, System.IO.FileMode.OpenOrCreate); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs); bw.Write("截止日期"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Year)); bw.Write("年"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Month)); bw.Write("月"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Day)); bw.Write("日"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Hour)); bw.Write("时"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Minute)); bw.Write("分"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Second)); bw.Write("秒"); bw.Write(System.Convert.ToDouble(((System.DateTime) this.endTime).Millisecond)); bw.Write("豪秒"); bw.Flush(); bw.Close(); fs.Close(); } catch (System.Exception arg_4BB_0) { KLineTestProcessor.ExceptionRecordFunc(arg_4BB_0.StackTrace); } this.bRegisterSuccFlag = true; MessageBox.Show("恭喜您,激活成功!", "提示", MessageBoxButtons.OK); this.dYear = System.Convert.ToDouble(((System.DateTime) this.endTime).Year); this.dMonth = System.Convert.ToDouble(((System.DateTime) this.endTime).Month); this.dDay = System.Convert.ToDouble(((System.DateTime) this.endTime).Day); this.dHour = System.Convert.ToDouble(((System.DateTime) this.endTime).Hour); this.dMinute = System.Convert.ToDouble(((System.DateTime) this.endTime).Minute); this.dSecond = System.Convert.ToDouble(((System.DateTime) this.endTime).Second); this.dMillisecond = System.Convert.ToDouble(((System.DateTime) this.endTime).Millisecond); base.Close(); } } else { MessageBox.Show("无效的激活码!", "提示", MessageBoxButtons.OK); this.bRegisterSuccFlag = false; } } } catch (System.Exception arg_5BE_0) { KLineTestProcessor.ExceptionRecordFunc(arg_5BE_0.StackTrace); MessageBox.Show("无效的激活码!", "提示", MessageBoxButtons.OK); this.bRegisterSuccFlag = false; } }
static void Main(string[] args) { if (!parse_args(args)) { show_usage(); return; } var d = new System.IO.DirectoryInfo(src_dir); var o = new System.IO.BinaryWriter(new System.IO.FileStream(ofname, System.IO.FileMode.Create)); // Write 32 kiB of zeros to the system area o.Write(new byte[32 * 1024]); List <VolumeDescriptor> voldescs = new List <VolumeDescriptor>(); // Add a primary volume descriptor var pvd = new PrimaryVolumeDescriptor(); voldescs.Add(pvd); ElToritoBootDescriptor bvd = null; if (bootEntries.Count > 0) { bvd = new ElToritoBootDescriptor(); voldescs.Add(bvd); } voldescs.Add(new VolumeDescriptorSetTerminator()); // Generate directory tree List <AnnotatedFSO> files, dirs; var afso = AnnotatedFSO.BuildAFSOTree(d, out dirs, out files); // Allocate space for files + directories int cur_lba = 0x10 + voldescs.Count; List <AnnotatedFSO> output_order = new List <AnnotatedFSO>(); AnnotatedFSO afso_bc = null; foreach (var file in files) { if (file.fsi is BootCatalogFileInfo) { afso_bc = file; continue; } var fi = file.fsi as FileInfo; var l = align(fi.Length); var lbal = l / 2048; file.lba = cur_lba; file.len = (int)fi.Length; cur_lba += (int)lbal; output_order.Add(file); foreach (var bfe in bootEntries) { if (bfe.ffname != null && bfe.boot_table && bfe.ffname == fi.FullName) { file.needs_boot_table = true; bfe.afso_boot_file = file; } } } // create boot catalog List <byte> bc = new List <byte>(); var bc_lba = cur_lba; if (bootEntries.Count > 0) { // Validation entry List <byte> val_ent = new List <byte>(); val_ent.Add(0x01); if (bootEntries[0].type == BootEntry.BootType.BIOS) { val_ent.Add(0); } else { val_ent.Add(0xef); } val_ent.Add(0); val_ent.Add(0); //val_ent.AddRange(Encoding.ASCII.GetBytes("isomake".PadRight(24))); for (int i = 0; i < 24; i++) { val_ent.Add(0); } var cs = elt_checksum(val_ent, 0xaa55); val_ent.Add((byte)(cs & 0xff)); val_ent.Add((byte)((cs >> 8) & 0xff)); val_ent.Add(0x55); val_ent.Add(0xaa); bc.AddRange(val_ent); // default entry List <byte> def_ent = new List <byte>(); if (bootEntries[0].bootable) { def_ent.Add(0x88); } else { def_ent.Add(0x00); } switch (bootEntries[0].etype) { case BootEntry.EmulType.Floppy: def_ent.Add(0x02); break; case BootEntry.EmulType.Hard: def_ent.Add(0x04); break; case BootEntry.EmulType.NoEmul: def_ent.Add(0x00); break; default: throw new NotSupportedException(); } def_ent.AddRange(BitConverter.GetBytes((ushort)bootEntries[0].load_seg)); def_ent.Add(0x0); def_ent.Add(0x0); def_ent.AddRange(BitConverter.GetBytes((ushort)bootEntries[0].sector_count)); if (bootEntries[0].afso_boot_file != null) { def_ent.AddRange(BitConverter.GetBytes(bootEntries[0].afso_boot_file.lba)); } else { def_ent.AddRange(BitConverter.GetBytes((int)0)); } for (int i = 0; i < 20; i++) { def_ent.Add(0); } bc.AddRange(def_ent); for (int idx = 1; idx < bootEntries.Count; idx++) { // section header List <byte> sh = new List <byte>(); if (idx == bootEntries.Count - 1) { sh.Add(0x91); } else { sh.Add(0x90); } if (bootEntries[idx].type == BootEntry.BootType.BIOS) { sh.Add(0x0); } else { sh.Add(0xef); } sh.AddRange(BitConverter.GetBytes((ushort)1)); for (int i = 0; i < 28; i++) { sh.Add(0); } //sh.AddRange(Encoding.ASCII.GetBytes(bootEntries[idx].type.ToString().PadRight(28))); bc.AddRange(sh); // section entry List <byte> se = new List <byte>(); if (bootEntries[idx].bootable) { se.Add(0x88); } else { se.Add(0x00); } switch (bootEntries[idx].etype) { case BootEntry.EmulType.Floppy: se.Add(0x02); break; case BootEntry.EmulType.Hard: se.Add(0x04); break; case BootEntry.EmulType.NoEmul: se.Add(0x00); break; default: throw new NotSupportedException(); } se.AddRange(BitConverter.GetBytes((ushort)bootEntries[idx].load_seg)); se.Add(0); se.Add(0); se.AddRange(BitConverter.GetBytes((ushort)bootEntries[idx].sector_count)); if (bootEntries[idx].afso_boot_file != null) { se.AddRange(BitConverter.GetBytes((int)bootEntries[idx].afso_boot_file.lba)); } else { se.AddRange(BitConverter.GetBytes((int)0)); } se.Add(0); for (int i = 0; i < 19; i++) { se.Add(0); } bc.AddRange(se); } afso_bc.lba = bc_lba; afso_bc.len = bc.Count; cur_lba += (int)align(bc.Count) / 2048; } // create root dir first entry continuation area containing rockridge attribute if required rr_ce = new List <byte>(); if (do_rr) { // Use a spare sector to contain the 'ER' field as is it too big for the system use area // This is later referenced in a 'CE' entry rr_ce_lba = cur_lba++; // Add SUSP ER field to identify RR rr_ce.Add(0x45); rr_ce.Add(0x52); // "ER" var ext_id = "IEEE_P1282"; var ext_desc = "THE IEEE P1282 PROTOCOL PROVIDES SUPPORT FOR POSIX FILE SYSTEM SEMANTICS."; var ext_src = "PLEASE CONTACT THE IEEE STANDARDS DEPARTMENT, PISCATAWAY, NJ, USA FOR THE P1282 SPECIFICATION."; rr_ce.Add((byte)(8 + ext_id.Length + ext_desc.Length + ext_src.Length)); // length rr_ce.Add(1); // version rr_ce.Add((byte)ext_id.Length); // LEN_ID rr_ce.Add((byte)ext_desc.Length); // LEN_DES rr_ce.Add((byte)ext_src.Length); // LEN_SRC rr_ce.Add(1); // EXT_VER rr_ce.AddRange(Encoding.ASCII.GetBytes(ext_id)); rr_ce.AddRange(Encoding.ASCII.GetBytes(ext_desc)); rr_ce.AddRange(Encoding.ASCII.GetBytes(ext_src)); } // build directory tree from most deeply nested to most shallow, so that we automatically patch up // the appropriate child lbas as we go List <byte> dir_tree = new List <byte>(); var dt_lba = cur_lba; Dictionary <int, AnnotatedFSO> parent_dir_map = new Dictionary <int, AnnotatedFSO>(); for (int i = 7; i >= 0; i--) { var afso_level = afso[i]; foreach (var cur_afso in afso_level) { build_dir_tree(cur_afso, dir_tree, dt_lba, parent_dir_map); } } // patch up parent lbas foreach (var kvp in parent_dir_map) { var lba = kvp.Value.lba; var len = kvp.Value.len; var lba_b = int_lsb_msb(lba); var len_b = int_lsb_msb(len); insert_bytes(lba_b, kvp.Key + 2, dir_tree); insert_bytes(len_b, kvp.Key + 10, dir_tree); } // And root directory entry var root_entry = build_dir_entry("\0", afso[0][0].lba, afso[0][0].len, d); cur_lba += dir_tree.Count / 2048; // create path table var path_table_l_lba = cur_lba; byte[] path_table_l = build_path_table(afso, true); var path_table_b_lba = path_table_l_lba + (int)align(path_table_l.Length) / 2048; byte[] path_table_b = build_path_table(afso, false); cur_lba = path_table_b_lba + (int)align(path_table_b.Length) / 2048; // Set pvd entries pvd.WriteString("VolumeIdentifier", "UNNAMED"); pvd.WriteInt("VolumeSpaceSize", cur_lba); pvd.WriteInt("VolumeSetSize", 1); pvd.WriteInt("VolumeSequenceNumber", 1); pvd.WriteInt("LogicalBlockSize", 2048); pvd.WriteInt("PathTableSize", path_table_l.Length); pvd.WriteInt("LocTypeLPathTable", path_table_l_lba); pvd.WriteInt("LocTypeMPathTable", path_table_b_lba); pvd.WriteBytes("RootDir", root_entry); if (bootEntries.Count > 0) { bvd.BootCatalogAddress = bc_lba; } // Write out volume descriptors foreach (var vd in voldescs) { vd.Write(o); } // files foreach (var f in output_order) { o.Seek(f.lba * 2048, SeekOrigin.Begin); var fin = new BinaryReader(((FileInfo)f.fsi).OpenRead()); var b = fin.ReadBytes(f.len); if (f.needs_boot_table) { // patch in the eltorito boot info table to offset 8 // first get 32 bit checksum from offset 64 onwards uint csum = elt_checksum32(b, 64); insert_bytes(BitConverter.GetBytes((int)0x10), 8, b); insert_bytes(BitConverter.GetBytes((int)f.lba), 12, b); insert_bytes(BitConverter.GetBytes((int)f.len), 16, b); insert_bytes(BitConverter.GetBytes(csum), 20, b); } o.Write(b, 0, f.len); } // directory records o.Seek(dt_lba * 2048, SeekOrigin.Begin); o.Write(dir_tree.ToArray(), 0, dir_tree.Count); // path tables o.Seek(path_table_l_lba * 2048, SeekOrigin.Begin); o.Write(path_table_l, 0, path_table_l.Length); o.Seek(path_table_b_lba * 2048, SeekOrigin.Begin); o.Write(path_table_b, 0, path_table_b.Length); // boot catalog if (bootEntries.Count > 0) { o.Seek(bc_lba * 2048, SeekOrigin.Begin); o.Write(bc.ToArray(), 0, bc.Count); } // rr es field continuation area if (rr_ce != null) { o.Seek(rr_ce_lba * 2048, SeekOrigin.Begin); o.Write(rr_ce.ToArray(), 0, rr_ce.Count); } // Align to sector size o.Seek(0, SeekOrigin.End); while ((o.BaseStream.Position % 2048) != 0) { o.Write((byte)0); } // Add 300k padding - required for VirtualBox it seems // According to 'man xorriso': // "This is a traditional remedy for a traditional bug in block device read drivers." for (int i = 0; i < 300 * 1024 / 4; i++) { o.Write((int)0); } o.Close(); }
private void DownLoadFile() { //临时文件夹 string tempFolderPath = Path.Combine(_SystemBinUrl, _TempFolder); if (!Directory.Exists(tempFolderPath)) { Directory.CreateDirectory(tempFolderPath); } //总进度条 if (progressBarTotal.InvokeRequired) { progressBarTotal.Invoke((ThreadStart) delegate { progressBarTotal.Maximum = downloadFileList.Count; }); } #region 载文件 UpdateFileInfo mFileInfo = null; string fileSavePath = ""; int i = 1; foreach (DownloadFileInfo file in this.downloadFileList) { //正在下载的文件名称 ShowCurrentlabelText(file.FileName); //文件信息 string filePath = Path.Combine(tempFolderPath, file.FileFullName); DirectoryHelper.CreateDirectoryByFilePath(filePath); mFileInfo = new UpdateFileInfo(); mFileInfo.FileName = filePath; //本地文件名,包括路径 mFileInfo.FileSaveName = file.FileFullName; //要下载的文件名称 mFileInfo.FileCategory = ""; //开始下载文件 mFileInfo = Proxy.DownLoadFile(mFileInfo); if (!string.IsNullOrEmpty(mFileInfo.ErrorMessage)) { ShowCurrentlabelText(mFileInfo.ErrorMessage); break; } if (mFileInfo != null && mFileInfo.FileData != null && mFileInfo.FileData.Count > 0) { fileSavePath = mFileInfo.FileName; while (mFileInfo.Length != mFileInfo.Offset) //循环的读取文件,上传,直到文件的长度等于文件的偏移量 { if (mFileInfo.Offset != 0) { mFileInfo = Proxy.DownLoadFile(mFileInfo); } if (mFileInfo.FileData == null || mFileInfo.FileData.Count < 1) { break; } using (System.IO.FileStream fs = new System.IO.FileStream(fileSavePath, System.IO.FileMode.OpenOrCreate)) { long offset = mFileInfo.Offset; //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加 using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs)) //初始化文件写入器 { writer.Seek((int)offset, System.IO.SeekOrigin.Begin); //设置文件的写入位置 writer.Write(mFileInfo.FileData.ToArray()); //写入数据 mFileInfo.Offset = fs.Length; //返回追加数据后的文件位置 mFileInfo.FileData = null; if (writer != null) { writer.Close(); } } if (fs != null) { fs.Close(); } }//end using (System.IO.FileStream fs = new System.IO.FileStream(fileSavePath, System.IO.FileMode.OpenOrCreate)) //进度条 int percentValue = (int)(((decimal)mFileInfo.Offset / (decimal)mFileInfo.Length) * (decimal)100); if (progressBarCurrent.InvokeRequired) { progressBarCurrent.Invoke((ThreadStart) delegate { progressBarCurrent.Value = percentValue; //System.Threading.Thread.Sleep(300); }); } } //end while (mFileInfo.Length != mFileInfo.Offset) } //end if (mFileInfo != null && mFileInfo.FileData != null && mFileInfo.FileData.Count > 0) //总进度 if (progressBarTotal.InvokeRequired) { progressBarTotal.Invoke((ThreadStart) delegate { progressBarTotal.Value = i; System.Threading.Thread.Sleep(300); }); } i++; } if (this.downloadFileList.Count == (i - 1)) { this.downloadFileList.Clear(); } #endregion #region 处理下载 this.Invoke(new MethodInvoker(delegate { buttonOk.Enabled = false; })); //Debug.WriteLine("All Downloaded"); foreach (DownloadFileInfo file in this.allFileList) { //string tempUrlPath = Utility.GetFolderUrl(file,_SystemBinUrl,_TempFolder); string oldPath = string.Empty; string newPath = string.Empty; try { oldPath = Path.Combine(_SystemBinUrl, file.FileFullName); newPath = Path.Combine(_SystemBinUrl + _TempFolder, file.FileFullName); //if (!string.IsNullOrEmpty(tempUrlPath)) //{ // oldPath = Path.Combine(_SystemBinUrl + tempUrlPath.Substring(1), file.FileName); // newPath = Path.Combine(_SystemBinUrl + _TempFolder + tempUrlPath, file.FileName); //} //else //{ // oldPath = Path.Combine(_SystemBinUrl, file.FileName); // newPath = Path.Combine(_SystemBinUrl + _TempFolder, file.FileName); //} ////just deal with the problem which the files EndsWith xml can not download //System.IO.FileInfo f = new FileInfo(newPath); //if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml")) //{ // ShowErrorAndRestartApplication(); //} //Added for dealing with the config file download errors string newfilepath = string.Empty; if (newPath.Substring(newPath.LastIndexOf(".") + 1).Equals("config_")) { if (System.IO.File.Exists(newPath)) { if (newPath.EndsWith("_")) { newfilepath = newPath; newPath = newPath.Substring(0, newPath.Length - 1); oldPath = oldPath.Substring(0, oldPath.Length - 1); } File.Move(newfilepath, newPath); } } //End added Utility.MoveFolderToOld(oldPath, newPath); //if (File.Exists(oldPath)) //{ // Utility.MoveFolderToOld(oldPath, newPath); //} //else //{ // //Edit for config_ file // if (!string.IsNullOrEmpty(tempUrlPath)) // { // if (!Directory.Exists(_SystemBinUrl + tempUrlPath.Substring(1))) // { // Directory.CreateDirectory(_SystemBinUrl + tempUrlPath.Substring(1)); // Utility.MoveFolderToOld(oldPath, newPath); // } // else // { // Utility.MoveFolderToOld(oldPath, newPath); // } // } // else // { // Utility.MoveFolderToOld(oldPath, newPath); // } //} } catch (Exception) { //log the error message,you can use the application's log code } } #endregion this.allFileList.Clear(); //下载完成 if (this.downloadFileList.Count == 0) { Exit(true); } else//下载出问题 { Exit(false); } }
/// <summary> /// Converts a PNG image into an ICON in specified sizes. /// </summary> /// <param name="pngFile">The PNG image stream</param> /// <param name="outputIcon">The ICON output stream</param> /// <param name="outputSizes">Specify different icon sizes to include in output file. All the sizes must be different. </param> public static void Convert(Stream inputStream, Stream outputStream, Size[] outputSizes, bool keepAspectRatio = false) { //Create the binary writer object used to write the data to the output stream. var writer = new System.IO.BinaryWriter(outputStream); try { //Check the input stream if (inputStream == null || inputStream.CanRead == false) { throw new System.IO.IOException("Invalid Input File (the input stream is un-readable)"); } /// HEADERS /// BYTE ORDER: LITTLE-ENDIAN /// ------------------------------------------- /// --OFFSET---SIZE---DESCRIPTION-------------- /// | 0 | 2 | Reserved. Must be 0. /// | 2 | 2 | Image type. 1 for icon (.ico), 2 for cursor. Other values are invalid /// | 4 | 2 | Specifies number of images in the file. /// | | 6 | Total size of file header /// ------------------------------------------- /// -------ICONDIRENTRY-STRUCTURE-------------- /// ------------------------------------------- /// --OFFSET---SIZE---DESCRIPTION-------------- /// | 0 | 1 | Image width in pixels. 0-255. 0 = 256. /// | 1 | 1 | Image height in pixels. 0-255. 0 = 256. /// | 2 | 1 | Number of colors in palette. 0 if no color pallete is used. /// | 3 | 1 | Reserved. Should be 0. /// | 4 | 2 | Color Planes: Should be 0 or 1. /// | 6 | 2 | Specifies bits per pixel. /// | 8 | 4 | Size of image data in bytes /// | 12 | 4 | Offset of the actual image data in the file. /// | | 16 | Total size of one imagedirentry. /// ------------------------------------------- /////////////// /// ALGORITHM /// 1. Write the main file headers (i.e. Type of the image, and number of images it contains) /// 2. Calculate the size of headers of all the icon variants (sizes) using method: /// totalHeadersSize = mainHeaderSize + (numberOfVariants * size of one imagedirentry) /// 3. Create empty image array for variants. Read images in all the streams scaled with different size. /// 4. Iterate all the image streams and write imagedirentry for each /// 4. a. The imagedirentry's offset will be totalHeadersSize + headers already processed. /// 5. Iterate all the image streams again and write the image data for each. SetStatus("Writing headers..."); //Offset: 0. Data: Must be zero (reserved). Size: 2 bytes. writer.Write((short)0); //Offset: 2. Data: Image type (1 for icon). Size: 2 bytes. writer.Write((short)1); //Offset: 4. Data: Number of images in the file. Size: 2 bytes. writer.Write((short)outputSizes.Length); SetStatus("Loading image..."); /// ICONDIRENTRY long headerSize = 6 + (outputSizes.Length * 16); //Read all the different image size variants in memory. MemoryStream[] imgStreams = new MemoryStream[outputSizes.Length]; for (int i = 0; i < imgStreams.Length; i++) { var inputImage = (Bitmap)Image.FromStream(inputStream).Resize(outputSizes[i], keepAspectRatio); imgStreams[i] = new MemoryStream(); inputImage.Save(imgStreams[i], System.Drawing.Imaging.ImageFormat.Png); } //Iterate all the size variables and write icon dir entry for each. Having offset values of headerSize + imgStreams[i].Length + lengthOfProcessedImages long totalProcessed = 0; for (int i = 0; i < imgStreams.Length; i++) { SetStatus($"Writing entries {i + 1} of {imgStreams.Length}..."); int offset = (int)(headerSize + totalProcessed); var size = outputSizes[i]; //Write icondirentry headers //Offset: 0. Data: Image width in pixels. Size: 1 byte. Min: 1. Max: 255. 0=256 writer.Write((byte)size.Width); //Offset: 1. Data: Image height in pixels. Size: 1 byte. Min: 1. Max: 255. 0=256 writer.Write((byte)size.Height); //Offset: 2. Data: No. of Color Palettes. Size: 1 byte. 0 = None. writer.Write((byte)0); //Offset: 3. Data: Reserverd (must be zero). Size: 1 byte. writer.Write((byte)0); //Offset: 4. Data: Color Planes. Size: 2 bytes. Should be 0 or 1. writer.Write((short)0); //Offset: 6. Data: Bits per pixel. Size: 2 bytes. using 32 bits per pixel. writer.Write((short)32); //Offset: 8. Data: Size of PNG image data. Size: 4 bytes. writer.Write((int)imgStreams[i].Length); //Offset: 12. Data: PNG image data offset in the file. Size: 4 bytes. writer.Write(offset); //Flush the binary writer. writer.Flush(); //Increment the counter so that next header can write correct image data offset. totalProcessed += imgStreams[i].Length; } //Iterate through all imgStreams and write them to the final stream. for (int i = 0; i < imgStreams.Length; i++) { SetStatus($"Writing image data {i + 1} of {imgStreams.Length}..."); writer.Write(imgStreams[i].ToArray()); writer.Flush(); } //Close the streams. writer.Close(); writer = null; } catch (Exception ex) { writer.Close(); writer = null; SetStatus("ERROR. " + ex.Message); throw ex; } }
private void f16_ButtonEncryptFile_Click(object sender, EventArgs e) { f16_labelPB.Text = "Проверка ключа..."; f16_labelPB.Update(); if (Key.Length != 8) { MessageBox.Show("Необходимо ввести ключ длиной 8 байт", "Ошибка"); f16_labelPB.Text = "Готов к работе"; f16_labelPB.Update(); goto exit_label; } CheckWeaknessOfKey(); progressBar.Value = 0; LinkedList <byte> File = new LinkedList <byte>(); f16_labelPB.Text = "Выбор файла..."; f16_labelPB.Update(); OpenFileDialog Load = new OpenFileDialog(); if (Load.ShowDialog() == DialogResult.OK) { f16_labelPB.Text = "Считываем из файла..."; f16_labelPB.Update(); System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default); while (reader.PeekChar() > -1) { File.AddLast(reader.ReadByte()); } reader.Close(); } else { f16_labelPB.Text = "Готов к работе"; f16_labelPB.Update(); return; } File.AddLast(0x80); while (File.Count % 8 != 0) { File.AddLast(0x00); } byte[] Original = File.ToArray(); File.Clear(); progressBar.Maximum = Original.Length / 8; f16_labelPB.Text = "Зашифровываем..."; f16_labelPB.Update(); byte[] Ciphertext; Cryption(true, ref Original, out Ciphertext); SaveFileDialog Save = new SaveFileDialog(); if (Save.ShowDialog() == DialogResult.OK) { f16_labelPB.Text = "Сохраняем результат в файл..."; f16_labelPB.Update(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(Save.FileName, System.IO.FileMode.OpenOrCreate), Encoding.Default); foreach (var b in Ciphertext) { writer.Write(b); } writer.Close(); } else { f16_labelPB.Text = "Готов к работе"; f16_labelPB.Update(); return; } f16_labelPB.Text = "Готово."; f16_labelPB.Update(); exit_label :; }
protected void btnDispAadhar_Click(object sender, EventArgs e) { Button btn = (Button)sender; GridViewRow gvr = (GridViewRow)btn.NamingContainer; int rowindex = gvr.RowIndex; string ApplicationNumber = ArivugvCWApprove.DataKeys[rowindex].Values["ApplicationNumber"].ToString(); string filepath = HttpContext.Current.Server.MapPath("~/DownloadFiles/"); string filename1 = ApplicationNumber + "Aadhar1.png"; string filename2 = ApplicationNumber + "Aadhar2.png"; string filename3 = ApplicationNumber + "Aadhar.pdf"; string sPathToSaveFileTo1 = filepath + filename1; string sPathToSaveFileTo2 = filepath + filename2; string sPathToSaveFileTo3 = filepath + filename3; string DBFile = "ImgAadharFront"; //ViewFile(DBFile, ApplicationNumber, filename, sPathToSaveFileTo, "[KACDC].[dbo].[ArivuEduLoan]"); using (kvdConn) { kvdConn.Open(); using (SqlCommand cmd = new SqlCommand("select ImgAadharFront,ImgAadharBack from [KACDC].[dbo].[ArivuEduLoan] where [ApplicationNumber]='" + ApplicationNumber + "' ", kvdConn)) { using (SqlDataReader dr1 = cmd.ExecuteReader(System.Data.CommandBehavior.Default)) { if (dr1.Read()) { // read in using GetValue and cast to byte array byte[] fileData1 = ((byte[])dr1["ImgAadharFront"]); // write bytes to disk as file using (System.IO.FileStream fs = new System.IO.FileStream(sPathToSaveFileTo1, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { // use a binary writer to write the bytes to disk using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData1); bw.Close(); } } byte[] fileData2 = ((byte[])dr1["ImgAadharBack"]); // write bytes to disk as file using (System.IO.FileStream fs = new System.IO.FileStream(sPathToSaveFileTo2, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { // use a binary writer to write the bytes to disk using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData2); bw.Close(); } } } dr1.Close(); } } } using (var doc1 = new iTextSharp.text.Document()) { PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream(sPathToSaveFileTo3, FileMode.Create)); doc1.Open(); //Add the Image file to the PDF document object. iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(sPathToSaveFileTo1); iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(sPathToSaveFileTo2); doc1.Add(new Paragraph("AAdhar Front")); doc1.Add(img1); doc1.Add(new Paragraph("AAdhar Back")); doc1.Add(img2); doc1.Close(); } //Download the PDF file. //Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=ImageExport.pdf"); //Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.Write(pdfDoc); //Response.End(); callaadhar(filename3); }
public void writeToFile(string path) { System.IO.FileStream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(fileStream); binaryWriter.Write(4); binaryWriter.Write(this.spectatorClientVersion.Length); binaryWriter.Write(this.spectatorClientVersion); binaryWriter.Write(this.gameId); binaryWriter.Write(this.gameEndStartupChunkId); binaryWriter.Write(this.gameStartChunkId); binaryWriter.Write(this.gameEndChunkId); binaryWriter.Write(this.gameEndKeyFrameId); binaryWriter.Write(this.gameLength); binaryWriter.Write(this.gameDelayTime); binaryWriter.Write(this.gameClientAddLag); binaryWriter.Write(this.gameChunkTimeInterval); binaryWriter.Write(this.gameKeyFrameTimeInterval); //binaryWriter.Write(this.gameELOLevel); binaryWriter.Write(this.gameLastChunkTime); binaryWriter.Write(this.gameLastChunkDuration); binaryWriter.Write(this.gamePlatform.Length); binaryWriter.Write(this.gamePlatform); binaryWriter.Write(this.observerEncryptionKey.Length); binaryWriter.Write(this.observerEncryptionKey); //binaryWriter.Write(this.gameCreateTime.Length); //binaryWriter.Write(this.gameCreateTime); //binaryWriter.Write(this.gameStartTime.Length); //binaryWriter.Write(this.gameStartTime); //binaryWriter.Write(this.gameEndTime.Length); //binaryWriter.Write(this.gameEndTime); binaryWriter.Write(this.lolVersion.Length); binaryWriter.Write(this.lolVersion); binaryWriter.Write(this.hasResult); if (this.hasResult) { binaryWriter.Write(this.endOfGameStatsBytes.Length); binaryWriter.Write(this.endOfGameStatsBytes); } if (this.players != null) { binaryWriter.Write(true); binaryWriter.Write(this.players.Length); PlayerInfo[] array = this.players; for (int i = 0; i < array.Length; i++) { PlayerInfo playerInfo = array[i]; char[] array2 = playerInfo.playerName.ToCharArray(); binaryWriter.Write(array2.Length); binaryWriter.Write(array2); char[] array3 = playerInfo.championName.ToCharArray(); binaryWriter.Write(array3.Length); binaryWriter.Write(array3); binaryWriter.Write(playerInfo.team); binaryWriter.Write(playerInfo.clientID); } } else { binaryWriter.Write(false); } binaryWriter.Write(this.gameKeyFrames.Count); foreach (System.Collections.Generic.KeyValuePair <int, byte[]> current in this.gameKeyFrames) { binaryWriter.Write(current.Key); binaryWriter.Write(current.Value.Length); binaryWriter.Write(current.Value); } binaryWriter.Write(this.gameChunks.Count); foreach (System.Collections.Generic.KeyValuePair <int, byte[]> current2 in this.gameChunks) { binaryWriter.Write(current2.Key); binaryWriter.Write(current2.Value.Length); binaryWriter.Write(current2.Value); } binaryWriter.Close(); fileStream.Close(); this.relatedFileName = path; }