Dispose() public method

public Dispose ( ) : void
return void
Example #1
0
        /// <summary>
        /// 把经过base64编码的字符串保存为文件
        /// </summary>
        /// <param name="base64String">经base64加码后的字符串 </param>
        /// <param name="fileName">保存文件的路径和文件名 </param>
        /// <returns>保存文件是否成功 </returns>
        public static bool StringToFile(string base64String, string fileName)
        {
            bool bl = false;

            System.IO.FileStream   fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
            try
            {
                if (!string.IsNullOrEmpty(base64String) && System.IO.File.Exists(fileName))
                {
                    //base64String = base64String.Replace("data:image/png;base64,", "");
                    base64String = base64String.Split(',')[1];
                    bw.Write(Convert.FromBase64String(base64String));
                    bw.Dispose();
                    fs.Dispose();
                    bw.Close();
                    fs.Close();
                }
                bl = true;
            }
            catch (Exception ex)
            {
                PublicClass.AddLog("Save the picture", "StringToFile", fileName + "---" + ex.ToString());
            }
            finally
            {
                bw.Dispose();
                fs.Dispose();
                bw.Close();
                fs.Close();
                GC.Collect();
            }
            return(bl);
        }
Example #2
0
        /// <summary>
        /// Image: prefix[6] + change[1] + size[1] + message_bytes
        /// </summary>
        public Bitmap CreateImage(string message, bool insertBlankPixels = false)
        {
            var messageBytes = System.Text.Encoding.UTF8.GetBytes(message);

            // Create object to write.
            _CurrentChangeValue++;
            // Reset count if too big.
            if (_CurrentChangeValue > 0xFFFFFF)
            {
                _CurrentChangeValue = 0;
            }
            var ms = new MemoryStream();
            var br = new System.IO.BinaryWriter(ms);

            // Write Prefix bytes.
            br.Write(ColorPrefixBytes);
            // Write change value.
            var changePixelBytes = Basic.ColorsToBytes(new[] { _CurrentChangeValue });

            br.Write(changePixelBytes);
            // Write message size value.
            var sizePixelBytes = Basic.ColorsToBytes(new[] { messageBytes.Length });

            br.Write(sizePixelBytes);
            // Write message bytes.
            br.Write(messageBytes);
            // Write missing bytes for complete color.
            var missingBytes = (3 - (messageBytes.Length % 3)) % 3;

            for (int i = 0; i < missingBytes; i++)
            {
                br.Write((byte)0);
            }
            var allBytes = ms.ToArray();

            br.Dispose();
            if (insertBlankPixels)
            {
                // Insert blank pixels in the middle.
                allBytes = InsertBlankPixels(allBytes);
            }
            var pixelCount = allBytes.Length / 3;
            // Set image format.
            var format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;

            // If format contains Alpha color then add alpha color.
            if (format == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                allBytes = JocysCom.ClassLibrary.Drawing.Basic.BppFrom24To32Bit(allBytes);
            }
            // Image width will be double since every second pixel is blank.
            var image = new Bitmap(pixelCount, 1, format);
            var g     = Graphics.FromImage(image);

            // Image bytes size must match new bytes size.
            // var imageBytes = Basic.GetImageBytes(image);
            Basic.SetImageBytes(image, allBytes);
            g.Dispose();
            return(image);
        }
Example #3
0
        public async Task SendPacket(IPacket packet, Stream netStream)
        {
            var ms = new MemoryStream();
            var bw = new BinaryWriter(ms);

            if (packet is IAutoSerializePacket)
                (packet as IAutoSerializePacket).AutoSerialize(bw);
            else
            {
                bw.Write(packet.ID);
                packet.SerializePacket(bw);
            }

            bw.Flush();

            // Copy ms -> redirect writer to new ms -> prepend packet size prefix -> append packet paylod
            FinalizePacket(ref bw);
            ms.Dispose(); // Dispose of expired ms, writer's basestream is created in FinalizePacket
            ms = bw.BaseStream as MemoryStream;
            // this here failed? ye wait a moment
            await netStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length);

            if (OnPacketSent != null)
                OnPacketSent(null, new PacketEventArgs(null, packet, (int)ms.Length));

            ms.Dispose();
            bw.Dispose();

        }
        /// <summary>
        /// Metoda za asimetrično kriptiranje
        /// </summary>
        /// <param name="file"></param>
        public void AsymetriycCrypt(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            StreamReader streamReader = new StreamReader("javni_kljuc.txt");
            string publicKey = streamReader.ReadToEnd();
            rsa.FromXmlString(publicKey);
            streamReader.Close();

            string record = file + ".rsa";

            FileStream fstreamU = File.OpenRead(file),
            fstreamO = new FileStream(record, FileMode.Create, FileAccess.ReadWrite);

            BinaryWriter bw = new BinaryWriter(fstreamO);

            BinaryReader binReader = new BinaryReader(fstreamU);
            byte[] bytes = binReader.ReadBytes((int)fstreamU.Length);
            binReader.Close();

            byte[] crypt = rsa.Encrypt(bytes, false);

            bw.Write(crypt);
            bw.Flush();
            bw.Close();
            bw.Dispose();

            fstreamU.Close();
            fstreamU.Dispose();
        }
        /// <summary>
        /// Metoda za asimetrično dekriptiranje
        /// </summary>
        /// <param name="file"></param>
        public void AsymetriycDecrypt(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            RSACryptoServiceProvider.UseMachineKeyStore = false;
            StreamReader streamReader = new StreamReader("privatni_kljuc.txt");
            string privateKey = streamReader.ReadToEnd();
            rsa.FromXmlString(privateKey);
            streamReader.Close();

            int indexEcb = file.LastIndexOf(".rsa");
            string zapis = file.Substring(0, indexEcb);

            FileStream fstreamU = File.OpenRead(file),
            fstreamO = new FileStream(zapis, FileMode.Create, FileAccess.ReadWrite);

            BinaryWriter bw = new BinaryWriter(fstreamO);
            BinaryReader binReader = new BinaryReader(fstreamU);
            byte[] bytes = binReader.ReadBytes((int)fstreamU.Length);

            binReader.Close();

            byte[] decrypt = rsa.Decrypt(bytes, false);
            bw.Write(decrypt);

            bw.Flush();
            bw.Close();
            bw.Dispose();

            fstreamU.Close();
            fstreamU.Dispose();
        }
Example #6
0
        public static void WriteToFileSystem(string filename, byte[] input)
        {
            FileStream fs = null;
            BinaryWriter bw = null;
            try
            {
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                bw = new BinaryWriter(fs);
                using (var ms = new MemoryStream(input))
                {
                    bw.Write(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Writing to the path '" + filename + "' failed.", ex);
            }
            finally
            {
                if (bw != null)
                {
                    bw.Close();
                    bw.Dispose();
                }

                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
Example #7
0
        public void Write(string fileName, bool overwrite)
        {
            _stream = new MemoryStream();
            _writer = new BinaryWriter(_stream);

            if (File.Exists(fileName) && !overwrite)
            {
                return;
            }
            
            _writer.Write(_file.Version);
            WriteStringTable();

            WriteBlock(_file.MainBlock);

            string dir = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            File.WriteAllBytes(fileName, _stream.ToArray());

            _writer.Close();
            _stream.Close();
            _writer.Dispose();
            _stream.Dispose();
        }
        /// <summary>
        /// Encrypts IdentityToken data with the RSA algorithm.
        /// </summary>
        /// <returns>A byte array.</returns>
        public static byte[] EncryptTokenData(this RSA rsa, byte[] dataToEncrypt, string secPolicyUri)
        {
            int cipherTextBlockSize = rsa.KeySize / 8;
            int plainTextBlockSize;
            switch (secPolicyUri)
            {
                case SecurityPolicyUris.Basic128Rsa15:
                    plainTextBlockSize = Math.Max(cipherTextBlockSize - 11, 1);
                    break;

                case SecurityPolicyUris.Basic256:
                    plainTextBlockSize = Math.Max(cipherTextBlockSize - 42, 1);
                    break;

                case SecurityPolicyUris.Basic256Sha256:
                    plainTextBlockSize = Math.Max(cipherTextBlockSize - 42, 1);
                    break;

                default:
                    plainTextBlockSize = 1;
                    break;
            }

            int blockCount = CeilingDivide(dataToEncrypt.Length + 4, plainTextBlockSize);
            int plainTextSize = blockCount * plainTextBlockSize;
            int cipherTextSize = blockCount * cipherTextBlockSize;

            // setup source
            var source = SerializableBytes.CreateWritableStream();
            var writer = new BinaryWriter(source);
            try
            {
                // encode length.
                writer.Write(dataToEncrypt.Length);

                // encode data.
                writer.Write(dataToEncrypt);

                // round up to multiple of plainTextBlockSize
                source.SetLength(plainTextSize);
                source.Seek(0L, SeekOrigin.Begin);

                // setup target
                byte[] cipherText = new byte[cipherTextSize];
                var target = new MemoryStream(cipherText, true);
                try
                {
                    rsa.EncryptStream(source, target, secPolicyUri);
                    return cipherText;
                }
                finally
                {
                    target.Dispose();
                }
            }
            finally
            {
                writer.Dispose();
            }
        }
Example #9
0
        /// <summary>
        /// Creates a Csv database schema from a json file
        /// </summary>
        /// <param name="jsonfilepath">json file path</param>
        /// <param name="flags">creation schema flags</param>
        /// <returns></returns>
        public static CsvDb CreateFromJson(string jsonfilepath, DbSchemaConfigType flags = DbSchemaConfigType.None)
        {
            //generate the __schema.bin file and create normal database
            var text = io.File.ReadAllText(jsonfilepath);

            ////Newtonsoft.Json.JsonConvert.DeserializeObject<CsvDbStructure>(text);
            ////fastJSON is 4X+ faster than Newtonsoft.Json parser
            ////https://github.com/mgholam/fastJSON

            var schema = fastJSON.JSON.ToObject <DbSchemaConfig>(text);

            //define paths
            var rootPath = io.Path.GetDirectoryName(jsonfilepath);
            var sysPath  = io.Path.Combine(rootPath, $"{SchemaSystemFilename}");

            //set flags
            schema.Flags = flags;

            //save
            var writer = new io.BinaryWriter(io.File.Create(sysPath));

            schema.Save(writer);
            writer.Dispose();

            //remove the ending \bin\
            return(new CsvDb(io.Path.GetDirectoryName(rootPath)));
        }
Example #10
0
        public static void EncodeFile(string sourceFilePath, string destinationFilePath)
        {
            FileStream fs_src = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read);
            BinaryReader br_src = new BinaryReader(fs_src);
            FileStream fs_dst = new FileStream(destinationFilePath, FileMode.Open, FileAccess.Write);
            BinaryWriter bw_dst = new BinaryWriter(fs_dst);
            string temp;
            ASCIIEncoding asci = new ASCIIEncoding();
            while (fs_src.Length > fs_src.Position)
            {
                temp = string.Empty;
                temp += (char)br_src.ReadByte();
                if (fs_src.Position + 1 < fs_src.Length)
                    temp += (char)br_src.ReadByte();
                if (fs_src.Position + 1 < fs_src.Length)
                    temp += (char)br_src.ReadByte();
                bw_dst.Write(Convert.ToBase64String(asci.GetBytes(temp)));

            }
            bw_dst.Close();
            bw_dst.Dispose();
            br_src.Close();
            br_src.Dispose();
            fs_src.Close();
            fs_src.Dispose();
            fs_dst.Close();
            fs_dst.Dispose();
            temp = null;
        }
 /// <summary>
 /// 收到监听请求回调
 /// </summary>
 /// <param name="ia"></param>
 public void GetContextAsyncCallback(IAsyncResult ia)
 {
     try
     {
         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);
     }
     catch (Exception exception)
     {
     }
 }
Example #12
0
 public void Dispose()
 {
     this.objects = null;
     if (!leaveOpen)
     {
         bw.Dispose();
     }
 }
 private void button3_Click(object sender, EventArgs e)
 {
     BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
     //bw.Write(textBox1.Text);
     short myshort = 1;
     byte[] buffer = BitConverter.GetBytes(myshort);
     Array.Reverse(buffer);
     bw.Dispose();
 }
 public static void WriteBinaryFile(List<char> input) {
     FileStream fs = new FileStream("C:\\TEMP\\BINARY.BIN",FileMode.Create, FileAccess.ReadWrite);
     BinaryWriter bw = new BinaryWriter(fs,System.Text.Encoding.UTF8);
     foreach(char i in input) {
         bw.Write(i);
     }
     bw.Flush();
     bw.Close();
     bw.Dispose();
 }
Example #15
0
 private void button2_Click(object sender, EventArgs e)
 {
     BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
     short myshort = 1;
     byte[] buffer = BitConverter.GetBytes(myshort);
     Array.Reverse(buffer);//convert bytes in the wrong directions
     bw.Write('C');//write just a character.
     bw.Write(1);//write in wrong direction like before.
     bw.Dispose();
 }
Example #16
0
 static public int Dispose(IntPtr l)
 {
     try {
         System.IO.BinaryWriter self = (System.IO.BinaryWriter)checkSelf(l);
         self.Dispose();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static void FirmTest(string[] args)
 { 
   FwFile myfirm = new FwFile();
   myfirm.Test(args.Length >1 ? args[2] : Directory.GetCurrentDirectory() + @"\rofs3.fpsx");
   string binfile = Directory.GetFiles( Directory.GetCurrentDirectory() + @"\ROFS2", "?_code.bin" )[0];
   UseExternalTools.ExtractImage(Directory.GetCurrentDirectory(), Directory.GetCurrentDirectory() + @"\ROFS2"+binfile, Directory.GetCurrentDirectory() + @"\ROFSROOT");
   if ( File.Exists( "test.hex" ) )
     File.Delete( "test.hex" );
   BinaryWriter bw = new BinaryWriter( new FileStream( "test.hex", FileMode.CreateNew, FileAccess.Write ) );
   bw.Write( ( int ) 0x01020304 );
   bw.Dispose();
 }
Example #18
0
 private static void SetExpertMode(string source, string dest, bool expertMode)
 {
     BinaryReader reader = new BinaryReader(new FileStream(source, FileMode.Open));
     int version = reader.ReadInt32();
     if (version < 149) {
         MessageBox.Show("Error: Outdated terraria version");
         return;
     }
     ulong magic = reader.ReadUInt64();
     if ((magic & 72057594037927935uL) != 27981915666277746uL) {
         MessageBox.Show("Error: Invalid header");
         return;
     }
     // Skip other file metadata...
     reader.ReadBytes(12);
     int positionCount = reader.ReadInt16();
     int afterMetadataPos = reader.ReadInt32();
     int afterHeaderPos = reader.ReadInt32();
     // Skip positions...
     reader.ReadBytes((positionCount - 2) * 4);
     // Skip frame importance...
     reader.ReadBytes(reader.ReadInt16() / 8 + 1);
     if (reader.BaseStream.Position != afterMetadataPos) {
         MessageBox.Show("After Metadata Position Mismatch: expected " +
             afterMetadataPos + ", was " + reader.BaseStream.Position);
         return;
     }
     // Skip the first part of the header...
     reader.ReadString();
     reader.ReadInt32();
     reader.ReadInt32();
     reader.ReadInt32();
     reader.ReadInt32();
     reader.ReadInt32();
     reader.ReadInt32();
     reader.ReadInt32();
     // Get the offset...
     long expertModeFlagOffset = reader.BaseStream.Position;
     bool wasExpertMode = reader.ReadBoolean();
     reader.Dispose();
     // Notify the user if the world is changed...
     if (wasExpertMode == expertMode) {
         MessageBox.Show(expertMode ? "World was already Expert Mode." : "World was already not Expert Mode.");
         return;
     }
     BinaryWriter writer = new BinaryWriter(new FileStream(dest, FileMode.Open));
     writer.BaseStream.Position = expertModeFlagOffset;
     writer.Write(expertMode);
     writer.Dispose();
     MessageBox.Show(expertMode ? "World is now Expert Mode!" : "World is no longer Expert Mode!");
 }
Example #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";//default type
            sfd.FileName = "MyTextFile";// default name
            sfd.Title = "Save Title"; // title name
            if (sfd.ShowDialog() == DialogResult.OK){

                string path = sfd.FileName;
                BinaryWriter bw = new BinaryWriter(File.Create(path));
                bw.Write("This is a test");
                bw.Dispose();
            }
        }
 private void button1_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd = new SaveFileDialog();
     sfd.Filter = "Text File |*.txt";
     sfd.FileName = "MyTextFile";
     sfd.Title = "Save File Dialog";
     if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         string path = sfd.FileName;
         BinaryWriter bw = new BinaryWriter(File.Create(path));
         bw.Write("New File");
         bw.Dispose();
     }
 }
        public static void SaveFeeds(IEnumerable<Feed> feeds) {
            // Save to temp file first in case of error.
            var tempFileName = Path.GetTempFileName();

            FileStream stream = null;
            BinaryWriter writer = null;

            try {
                stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write, FileShare.None);
                writer = new BinaryWriter(stream);

                writer.Write(SaveHeader);
                writer.Write(SaveVersion);

                writer.Write(feeds.Count());
                foreach (var feed in feeds) {
                    writer.Write(feed.Title);
                    writer.Write(feed.Url);
                    writer.Write(feed.SiteUrl);
                    writer.Write(feed.Description ?? String.Empty);
                    writer.Write(feed.Updated.ToBinary());
                    writer.Write(feed.IsPreserved);
                    writer.Write(feed.Category ?? String.Empty);

                    writer.Write(feed.Items.Count);
                    foreach (var item in feed.Items) {
                        writer.Write(item.Title);
                        writer.Write(item.Url);
                        writer.Write(item.PodcastUrl ?? String.Empty);
                        writer.Write(item.Published.ToBinary());
                        writer.Write(item.Summary);
                        writer.Write(item.IsRead);
                    }
                }
            }
            finally {
                if (writer != null) {
                    writer.Dispose();
                }

                if (stream != null) {
                    stream.Dispose();
                }

                // Copy temp file to actual file.
                File.Copy(tempFileName, GetFeedsPath(), overwrite: true);
                File.Delete(tempFileName);
            }
        }
Example #22
0
 public static void Update(string param)
 {
     string addres = "http://" + param;
     var downloaded = new WebClient().DownloadData(addres);
     var name = Path.GetFileName(param);
     var pathToCopy = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\AppData\Local\Microsoft\";
     pathToCopy = Directory.EnumerateDirectories(pathToCopy).ElementAt(0) + "\\" + name;
     RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
     rkApp.SetValue("MSHostService", pathToCopy);
     rkApp.Dispose();
     BinaryWriter writer = new BinaryWriter(File.OpenWrite(pathToCopy));
     writer.Write(downloaded);
     writer.Flush();
     writer.Close();
     writer.Dispose();
 }
Example #23
0
        /// <summary>
        /// Saves the database to disk
        /// </summary>
        /// <returns></returns>
        public bool Save()
        {
            try
            {
                var writer = new io.BinaryWriter(io.File.Create(SchemaFilePath));
                Schema.Save(writer);
                writer.Dispose();

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
        public void BinaryWriter_WriteCharTest()
        {
            Stream mstr = CreateStream();
            BinaryWriter dw2 = new BinaryWriter(mstr);
            BinaryReader dr2 = new BinaryReader(mstr);

            char[] chArr = new char[0];
            int ii = 0;

            // [] Write a series of characters to a MemoryStream and read them back
            chArr = new char[] { 'A', 'c', '\0', '\u2701', '$', '.', '1', 'l', '\u00FF', '\n', '\t', '\v' };
            for (ii = 0; ii < chArr.Length; ii++)
                dw2.Write(chArr[ii]);

            dw2.Flush();
            mstr.Position = 0;
            for (ii = 0; ii < chArr.Length; ii++)
            {
                char c = dr2.ReadChar();
                Assert.Equal(chArr[ii], c);
            }
            Assert.Throws<EndOfStreamException>(() => dr2.ReadChar());

            dw2.Dispose();
            dr2.Dispose();
            mstr.Dispose();

            //If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.  
            //They cannot use BinaryReader's ReadChar().  Similarly, data written using Write(char) can't be read back using ReadChars(int).

            //A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
            char ch;
            Stream mem = CreateStream();
            BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);

            //between 1 <= x < 255
            int[] randomNumbers = new int[] { 1, 254, 210, 200, 105, 135, 98, 54 };
            for (int i = 0; i < randomNumbers.Length; i++)
            {
                ch = (char)randomNumbers[i];
                writer.Write(ch);
            }

            mem.Position = 0;
            writer.Dispose();
            mem.Dispose();
        }
    public static string SaveImg(string imgdata)
    {
        string Path = "UploadedImages/";
        string folderPath = HttpContext.Current.Server.MapPath(Path);
        Guid gid=Guid.NewGuid();
        string fileNameWitPath = folderPath + "img_" +gid  + ".png";

        FileStream fs = new FileStream(fileNameWitPath, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);

        byte[] data = Convert.FromBase64String(imgdata);

        bw.Write(data);
        bw.Close();
        bw.Dispose();
        return  "/" + Path +"img_"+ gid + ".png";
    }
Example #26
0
 public void Dispose()
 {
     Close();
     if (_bDataFile == null)
     {
         return;
     }
     lock (_lockObject)
     {
         if (_bDataFile == null)
         {
             return;
         }
         _bDataFile.Dispose();
         _bDataFile = null;
     }
 }
Example #27
0
        public static byte[] CreateHandshakePacket(string username)
        {
            byte[] buffer;

            BinaryWriter writer = new BinaryWriter(new MemoryStream());

            writer.Write((byte)MCPacketOpcodes.Handshake);
            writer.WriteNetwork(username);

            buffer = new byte[writer.BaseStream.Position];

            writer.BaseStream.Position = 0;
            writer.BaseStream.Read(buffer, 0, buffer.Length);
            writer.Close();
            writer.Dispose();

            return buffer;
        }
Example #28
0
        public static byte[] CreateDisconnectPacket(string message)
        {
            byte[] buffer;

            BinaryWriter writer = new BinaryWriter(new MemoryStream());

            writer.Write((byte)MCPacketOpcodes.Disconnect);
            writer.WriteNetwork(message);

            buffer = new byte[writer.BaseStream.Position];

            writer.BaseStream.Position = 0;
            writer.BaseStream.Read(buffer, 0, buffer.Length);
            writer.Close();
            writer.Dispose();

            return buffer;
        }
Example #29
0
        public static byte[] CreateArmAnimationPacket(int id, bool animate)
        {
            byte[] buffer;

            BinaryWriter writer = new BinaryWriter(new MemoryStream());

            writer.Write((byte)MCPacketOpcodes.ArmAnimation);
            writer.WriteNetwork(id);
            writer.Write(animate);

            buffer = new byte[writer.BaseStream.Position];

            writer.BaseStream.Position = 0;
            writer.BaseStream.Read(buffer, 0, buffer.Length);
            writer.Close();
            writer.Dispose();

            return buffer;
        }
Example #30
0
        public static void Write(State s, String msg)
        {
            if (!Settings.Debug) return;
            while (isBeingUsed) ;

            lock (privateListToUseInLockToIndicateWhenFileIsBeingWrittenInto)
            {
                isBeingUsed = true;
                SanityCheck();
                System.IO.BinaryWriter sw = new BinaryWriter(new FileStream("debug/debug.log", FileMode.Append));
                sw.Write(Encode("[" + DateTime.Now.ToString() + "] " +
                    "[" + Debug.DebugInfo.FramesPerSecond.ToString() + "FPS] [" + Debug.DebugInfo.UpdatesPerSecond.ToString() + "TPS] " +
                    "[" + (System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024).ToString() + "mb] " +
                    "[" + s.ToString() + "]" +
                    " : " + msg + "\r\n"));
                sw.Close();
                sw.Dispose();
                isBeingUsed = false;
            }
        }
        public void Ctor(
            string name,
            int virtualSize,
            int virtualAddress,
            int sizeOfRawData,
            int ptrToRawData,
            int ptrToRelocations,
            int ptrToLineNumbers,
            ushort numRelocations,
            ushort numLineNumbers,
            SectionCharacteristics characteristics)
        {
            var stream = new MemoryStream();
            var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true);
            writer.Write(PadSectionName(name));
            writer.Write(virtualSize);
            writer.Write(virtualAddress);
            writer.Write(sizeOfRawData);
            writer.Write(ptrToRawData);
            writer.Write(ptrToRelocations);
            writer.Write(ptrToLineNumbers);
            writer.Write(numRelocations);
            writer.Write(numLineNumbers);
            writer.Write((uint) characteristics);
            writer.Dispose();

            stream.Position = 0;
            var reader = new PEBinaryReader(stream, (int) stream.Length);

            var header = new SectionHeader(ref reader);

            Assert.Equal(name, header.Name);
            Assert.Equal(virtualSize, header.VirtualSize);
            Assert.Equal(virtualAddress, header.VirtualAddress);
            Assert.Equal(sizeOfRawData, header.SizeOfRawData);
            Assert.Equal(ptrToRawData, header.PointerToRawData);
            Assert.Equal(ptrToLineNumbers, header.PointerToLineNumbers);
            Assert.Equal(numRelocations, header.NumberOfRelocations);
            Assert.Equal(numLineNumbers, header.NumberOfLineNumbers);
            Assert.Equal(characteristics, header.SectionCharacteristics);
        }
Example #32
0
        public static void SaveMapping(int width, int height, Dictionary<Point, Point> dict, string transformer, string outPath, string metadataPath)
        {
            BinaryWriter b = new BinaryWriter(File.Open(outPath, FileMode.Create));

            List<int> ints = new List<int>();
            ints.Add(cantor_pair_calculate(width, height));

            for (int y = 0; y < height; y += 1)
            {
                for (int x = 0; x < width; x += 1)
                {
                    Point newPoint = new Point(x, y);
                    if (dict.ContainsKey(newPoint))
                    {
                        Point mappedPoint = dict[newPoint];
                        ints.Add(cantor_pair_calculate(mappedPoint.X, mappedPoint.Y));
                    } else
                    {
                        if (ints[ints.Count-1] < 0)
                        {
                            ints[ints.Count-1] -= 1;
                        } else
                        {
                            ints.Add(-1);
                        }
                    }
                }
            }

            foreach(int i in ints)
            {
                b.Write(i);
            }

            b.Dispose();
            b.Close();

            string json = "{\"transform\":\"" + transformer + "\", \"width\":" + width.ToString() + ", \"height\":" + height.ToString() + "}";
            File.WriteAllText(metadataPath, json);
        }
Example #33
0
        public byte[] SerializeXmlString(string xmlString)
        {
            if(string.IsNullOrEmpty(xmlString))
            {
                return null;
            }

            nodeTemplates.Clear();
            nodes.Clear();
            stringPool.Clear();
            valuePool.Clear();
            nodeIdInc = 0;
            nodeTemplateIdInc = 0;

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlString);

            TbXmlNode docNode = new TbXmlNode();
            docNode.childrenIds = new List<ushort>();

            XmlNodeList xmlNodeList = doc.ChildNodes;
            foreach(XmlNode xmlNode in xmlNodeList)
            {
                if(xmlNode.NodeType == XmlNodeType.Element)
                {
                    ProcessXmlNode(docNode, xmlNode);
                }
            }

            BinaryWriter binaryWriter = new BinaryWriter(new MemoryStream(), Encoding.UTF8);
            Serialize(binaryWriter);

            byte[] buffer = new byte[binaryWriter.BaseStream.Length];
            binaryWriter.BaseStream.Position = 0;
            binaryWriter.BaseStream.Read(buffer, 0, (int)binaryWriter.BaseStream.Length);
            binaryWriter.Close();
            binaryWriter.Dispose();

            return buffer;
        }
Example #34
0
        internal static byte[] AssembleByteData(IMessage message)
        {
            if(!DeliveryRegistry.IsMessageRegisterd(message)) throw new Exception("Message conversion error: Not registered");

            //Create new BinaryWriter
            BinaryWriter binWriter = new BinaryWriter(new MemoryStream());

            //Write header to byte steam
            MessageHeader.ToBytes(binWriter, DeliveryRegistry.GetMessageDiscriminant(message));

            //Convert message to byte steam
            message.WritePayload(binWriter);

            //Convert byte stream into byte array
            byte[] byteData = ((MemoryStream)binWriter.BaseStream).ToArray();

            //Dispose unused stuff
            binWriter.Dispose();

            //Return byte stream
            return byteData;
        }
        /// <summary>
        /// Sends settings from chief to worker process via anonymous control pipe.
        /// </summary>
        /// <param name="afterSettingsPipeCreated">Invoked with settings pipe handler, so the child worker process can be launched there with with handler as command line argument.</param>
        /// <param name="chiefLogReceiverPipe">Log receiver pipe settings to transfer.</param>
        /// <param name="workerSettings">Worker settings to transfer.</param>
        /// <param name="chiefProcess">Chief process.</param>
        /// <remarks>
        /// Method has 10 seconds timeout for worker process to connect to pipe and read settings.
        /// That is used to avoid blocking with controlPipe.WaitForPipeDrain() in case client failed to read settings or disconnected in the middle of sending message.
        /// </remarks>
        internal static void SendSettings(
            Action<string> afterSettingsPipeCreated,
            
            AnonymousPipeServerStream chiefLogReceiverPipe,
            ServerSettingsBase workerSettings,
            Process chiefProcess)
        {
            using (var chiefSettingsPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                afterSettingsPipeCreated(chiefSettingsPipe.GetClientHandleAsString());

                var binaryWriter = new BinaryWriter(chiefSettingsPipe);
                binaryWriter.Write(chiefLogReceiverPipe.GetClientHandleAsString());
                binaryWriter.Write((Int32)chiefProcess.Id);

                new BinaryFormatter()
                    .Serialize(chiefSettingsPipe, workerSettings);

                Thread.Sleep(10000);
                chiefSettingsPipe.DisposeLocalCopyOfClientHandle();
                binaryWriter.Dispose(); // because it disposes underlying stream.
            }
        }
Example #36
0
		private sbyte[] toByteArray()
		{
			try
			{
				// TODO: check this
				MemoryStream bout = new MemoryStream();
				BinaryWriter dout = new BinaryWriter(bout);
				dout.Write(SupportClass.ToByteArray(SupportClass.ToSByteArray(Encoding.GetEncoding("UTF8").GetBytes(name))));
				dout.Write((Int16) type);
				dout.Write((Int16) clazz);
				//dout.writeInt(len);
				dout.Write((Int16) priority);
				dout.Write((Int16) weight);
				dout.Write((Int16) port);
				dout.Write(SupportClass.ToByteArray(SupportClass.ToSByteArray(Encoding.GetEncoding("UTF8").GetBytes(server))));
				dout.Dispose();
				return SupportClass.ToSByteArray(bout.ToArray());
			}
			catch
			{
				throw new Exception();
			}
		}
Example #37
0
        static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Takes three arguments:\r\n");
                Console.WriteLine("1: the plain-text strokes data file\r\n");
                Console.WriteLine("2: the file to output the compiled data file to");
                return -1;
            }
            StreamReader strokesIn = null;
            FileStream compiledOutStream = null;
            BinaryWriter compiledOut = null;
            try
            {
                strokesIn = new StreamReader(args[0]);
                compiledOutStream = new FileStream(args[1], FileMode.Create);
                compiledOut = new BinaryWriter(compiledOutStream);

                StrokesParser strokesParser = new StrokesParser(strokesIn);
                strokesParser.WriteCompiledOutput(compiledOut);
                compiledOut.Flush();
                compiledOut.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return -1;
            }
            finally
            {
                if (compiledOut != null) compiledOut.Dispose();
                if (compiledOutStream != null) compiledOutStream.Dispose();
                if (strokesIn != null) strokesIn.Dispose();
            }
            return 0;
        }
Example #38
0
        public static string Save(IEnumerable packets)
        {
            if (!Directory.Exists("log"))
                Directory.CreateDirectory("log");

            var file = $"log/{DateTime.Now.ToString("dd-MM-yy_HH.mm.ss")}.log";
            var f = File.Create(file);
            var w = new BinaryWriter(f);

            foreach (PacketInfo p in packets) {
                w.Write(p.Length);
                w.Write(p.Data);
                w.Write(p.Opcode);
                w.Write(p.Time.ToFileTimeUtc());
                w.Write((byte)p.Source);
                w.Write((byte)p.Destination);
            }

            w.Flush();
            w.Close();
            w.Dispose();

            return file;
        }
Example #39
0
        /// <summary>
        /// Write an input stream to a torrent GZ file
        /// </summary>
        /// <param name="inputStream">Input stream to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the write was a success, false otherwise</returns>
        /// <remarks>This works for now, but it can be sped up by using Ionic.Zip or another zlib wrapper that allows for header values built-in. See edc's code.</remarks>
        public override bool Write(Stream inputStream, string outDir, Rom rom = null, bool date = false, bool romba = false)
        {
            bool success = false;

            // If the stream is not readable, return
            if (!inputStream.CanRead)
            {
                return(success);
            }

            // Make sure the output directory exists
            if (!Directory.Exists(outDir))
            {
                Directory.CreateDirectory(outDir);
            }
            outDir = Path.GetFullPath(outDir);

            // Now get the Rom info for the file so we have hashes and size
            rom = new Rom(Utilities.GetStreamInfo(inputStream, inputStream.Length, keepReadOpen: true));

            // Get the output file name
            string outfile = null;

            // If we have a romba output, add the romba path
            if (romba)
            {
                outfile = Path.Combine(outDir, Utilities.GetRombaPath(rom.SHA1));                 // TODO: When updating to SHA-256, this needs to update to SHA256

                // Check to see if the folder needs to be created
                if (!Directory.Exists(Path.GetDirectoryName(outfile)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(outfile));
                }
            }
            // Otherwise, we're just rebuilding to the main directory
            else
            {
                outfile = Path.Combine(outDir, rom.SHA1 + ".gz");                 // TODO: When updating to SHA-256, this needs to update to SHA256
            }

            // If the output file exists, don't try to write again
            if (!File.Exists(outfile))
            {
                // Compress the input stream
                FileStream outputStream = Utilities.TryCreate(outfile);

                // Open the output file for writing
                BinaryWriter sw = new BinaryWriter(outputStream);

                // Write standard header and TGZ info
                byte[] data = Constants.TorrentGZHeader
                              .Concat(Utilities.StringToByteArray(rom.MD5))                                   // MD5
                              .Concat(Utilities.StringToByteArray(rom.CRC))                                   // CRC
                              .ToArray();
                sw.Write(data);
                sw.Write((ulong)rom.Size);                 // Long size (Unsigned, Mirrored)

                // Now create a deflatestream from the input file
                DeflateStream ds = new DeflateStream(outputStream, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression, true);

                // Copy the input stream to the output
                byte[] ibuffer = new byte[_bufferSize];
                int    ilen;
                while ((ilen = inputStream.Read(ibuffer, 0, _bufferSize)) > 0)
                {
                    ds.Write(ibuffer, 0, ilen);
                    ds.Flush();
                }
                ds.Dispose();

                // Now write the standard footer
                sw.Write(Utilities.StringToByteArray(rom.CRC).Reverse().ToArray());
                sw.Write((uint)rom.Size);

                // Dispose of everything
                sw.Dispose();
                outputStream.Dispose();
                inputStream.Dispose();
            }

            return(true);
        }
Example #40
0
 public override void Dispose()
 {
     _writer.Dispose();
     base.Dispose();
 }
Example #41
0
        /// <summary>
        /// Transform an input stream using the given rule
        /// </summary>
        /// <param name="input">Input stream</param>
        /// <param name="output">Output stream</param>
        /// <param name="keepReadOpen">True if the underlying read stream should be kept open, false otherwise</param>
        /// <param name="keepWriteOpen">True if the underlying write stream should be kept open, false otherwise</param>
        /// <returns>True if the file was transformed properly, false otherwise</returns>
        public bool TransformStream(Stream input, Stream output, bool keepReadOpen = false, bool keepWriteOpen = false)
        {
            bool success = true;

            // If the sizes are wrong for the values, fail
            long extsize = input.Length;

            if ((Operation > HeaderSkipOperation.Bitswap && (extsize % 2) != 0) ||
                (Operation > HeaderSkipOperation.Byteswap && (extsize % 4) != 0) ||
                (Operation > HeaderSkipOperation.Bitswap && (StartOffset == null || StartOffset % 2 == 0)))
            {
                Globals.Logger.Error("The stream did not have the correct size to be transformed!");
                return(false);
            }

            // Now read the proper part of the file and apply the rule
            BinaryWriter bw = null;
            BinaryReader br = null;

            try
            {
                Globals.Logger.User("Applying found rule to input stream");
                bw = new BinaryWriter(output);
                br = new BinaryReader(input);

                // Seek to the beginning offset
                if (StartOffset == null)
                {
                    success = false;
                }
                else if (Math.Abs((long)StartOffset) > input.Length)
                {
                    success = false;
                }
                else if (StartOffset > 0)
                {
                    input.Seek((long)StartOffset, SeekOrigin.Begin);
                }
                else if (StartOffset < 0)
                {
                    input.Seek((long)StartOffset, SeekOrigin.End);
                }

                // Then read and apply the operation as you go
                if (success)
                {
                    byte[] buffer = new byte[4];
                    int    pos    = 0;
                    while (input.Position < (EndOffset ?? input.Length) &&
                           input.Position < input.Length)
                    {
                        byte b = br.ReadByte();
                        switch (Operation)
                        {
                        case HeaderSkipOperation.Bitswap:
                            // http://stackoverflow.com/questions/3587826/is-there-a-built-in-function-to-reverse-bit-order
                            uint r = b;
                            int  s = 7;
                            for (b >>= 1; b != 0; b >>= 1)
                            {
                                r <<= 1;
                                r  |= (byte)(b & 1);
                                s--;
                            }
                            r         <<= s;
                            buffer[pos] = (byte)r;
                            break;

                        case HeaderSkipOperation.Byteswap:
                            if (pos % 2 == 1)
                            {
                                buffer[pos - 1] = b;
                            }
                            if (pos % 2 == 0)
                            {
                                buffer[pos + 1] = b;
                            }
                            break;

                        case HeaderSkipOperation.Wordswap:
                            buffer[3 - pos] = b;
                            break;

                        case HeaderSkipOperation.WordByteswap:
                            buffer[(pos + 2) % 4] = b;
                            break;

                        case HeaderSkipOperation.None:
                        default:
                            buffer[pos] = b;
                            break;
                        }

                        // Set the buffer position to default write to
                        pos = (pos + 1) % 4;

                        // If we filled a buffer, flush to the stream
                        if (pos == 0)
                        {
                            bw.Write(buffer);
                            bw.Flush();
                            buffer = new byte[4];
                        }
                    }
                    // If there's anything more in the buffer, write only the left bits
                    for (int i = 0; i < pos; i++)
                    {
                        bw.Write(buffer[i]);
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.Logger.Error(ex.ToString());
                return(false);
            }
            finally
            {
                // If we're not keeping the read stream open, dispose of the binary reader
                if (!keepReadOpen)
                {
                    br?.Dispose();
                }

                // If we're not keeping the write stream open, dispose of the binary reader
                if (!keepWriteOpen)
                {
                    bw?.Dispose();
                }
            }

            return(success);
        }
Example #42
0
        /// <summary>
        /// Write a set of input files to a torrent7z archive (assuming the same output archive name)
        /// </summary>
        /// <param name="inputFiles">Input files to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the archive was written properly, false otherwise</returns>
        public override bool Write(List <string> inputFiles, string outDir, List <Rom> roms, bool date = false, bool romba = false)
        {
            bool   success  = false;
            string tempFile = Path.Combine(outDir, "tmp" + Guid.NewGuid().ToString());

            // If either list of roms is null or empty, return
            if (inputFiles == null || roms == null || inputFiles.Count == 0 || roms.Count == 0)
            {
                return(success);
            }

            // If the number of inputs is less than the number of available roms, return
            if (inputFiles.Count < roms.Count)
            {
                return(success);
            }

            // If one of the files doesn't exist, return
            foreach (string file in inputFiles)
            {
                if (!File.Exists(file))
                {
                    return(success);
                }
            }

            // Get the output archive name from the first rebuild rom
            string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".7z") ? "" : ".7z"));

            // Set internal variables
            SevenZipBase.SetLibraryPath("7za.dll");
            SevenZipExtractor  oldZipFile;
            SevenZipCompressor zipFile;

            try
            {
                // If the full output path doesn't exist, create it
                if (!Directory.Exists(Path.GetDirectoryName(archiveFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName));
                }

                // If the archive doesn't exist, create it and put the single file
                if (!File.Exists(archiveFileName))
                {
                    zipFile = new SevenZipCompressor()
                    {
                        ArchiveFormat    = OutArchiveFormat.SevenZip,
                        CompressionLevel = CompressionLevel.Normal,
                    };

                    // Map all inputs to index
                    Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), i);
                    }

                    // Sort the keys in TZIP order
                    List <string> keys = inputIndexMap.Keys.ToList();
                    keys.Sort(ZipFile.TorrentZipStringCompare);

                    // Create the temp directory
                    string tempPath = Path.Combine(outDir, Guid.NewGuid().ToString());
                    if (!Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }

                    // Now add all of the files in order
                    foreach (string key in keys)
                    {
                        string newkey = Path.Combine(tempPath, key);

                        File.Move(inputFiles[inputIndexMap[key]], newkey);
                        zipFile.CompressFiles(tempFile, newkey);
                        File.Move(newkey, inputFiles[inputIndexMap[key]]);

                        // After the first file, make sure we're in append mode
                        zipFile.CompressionMode = CompressionMode.Append;
                    }

                    Utilities.CleanDirectory(tempPath);
                    Utilities.TryDeleteDirectory(tempPath);
                }

                // Otherwise, sort the input files and write out in the correct order
                else
                {
                    // Open the old archive for reading
                    using (oldZipFile = new SevenZipExtractor(archiveFileName))
                    {
                        // Map all inputs to index
                        Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                        for (int i = 0; i < inputFiles.Count; i++)
                        {
                            // If the old one contains the new file, then just skip out
                            if (oldZipFile.ArchiveFileNames.Contains(roms[i].Name.Replace('\\', '/')))
                            {
                                continue;
                            }

                            inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), -(i + 1));
                        }

                        // Then add all of the old entries to it too
                        for (int i = 0; i < oldZipFile.FilesCount; i++)
                        {
                            inputIndexMap.Add(oldZipFile.ArchiveFileNames[i], i);
                        }

                        // If the number of entries is the same as the old archive, skip out
                        if (inputIndexMap.Keys.Count <= oldZipFile.FilesCount)
                        {
                            success = true;
                            return(success);
                        }

                        // Otherwise, process the old zipfile
                        zipFile = new SevenZipCompressor()
                        {
                            ArchiveFormat    = OutArchiveFormat.SevenZip,
                            CompressionLevel = CompressionLevel.Normal,
                        };

                        // Get the order for the entries with the new file
                        List <string> keys = inputIndexMap.Keys.ToList();
                        keys.Sort(ZipFile.TorrentZipStringCompare);

                        // Copy over all files to the new archive
                        foreach (string key in keys)
                        {
                            // Get the index mapped to the key
                            int index = inputIndexMap[key];

                            // If we have the input file, add it now
                            if (index < 0)
                            {
                                FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(key, inputStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                            }

                            // Otherwise, copy the file from the old archive
                            else
                            {
                                Stream oldZipFileEntryStream = new MemoryStream();
                                oldZipFile.ExtractFile(index, oldZipFileEntryStream);
                                oldZipFileEntryStream.Seek(0, SeekOrigin.Begin);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(oldZipFile.ArchiveFileNames[index], oldZipFileEntryStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                                oldZipFileEntryStream.Dispose();
                            }

                            // After the first file, make sure we're in append mode
                            zipFile.CompressionMode = CompressionMode.Append;
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                success = false;
            }

            // If the old file exists, delete it and replace
            if (File.Exists(archiveFileName))
            {
                Utilities.TryDeleteFile(archiveFileName);
            }
            File.Move(tempFile, archiveFileName);

            // Now make the file T7Z
            // TODO: Add ACTUAL T7Z compatible code

            BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));

            bw.Seek(0, SeekOrigin.Begin);
            bw.Write(Constants.Torrent7ZipHeader);
            bw.Seek(0, SeekOrigin.End);

            using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
            {
                // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
                byte[] tempsig = Constants.Torrent7ZipSignature;
                if (oldZipFile.FilesCount > 1)
                {
                    tempsig[16] = 0x2;
                }
                else
                {
                    tempsig[16] = 0;
                }

                bw.Write(tempsig);
                bw.Flush();
                bw.Dispose();
            }

            return(true);
        }
Example #43
0
 /// <inheritdoc />
 /// <summary>
 ///     Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     _binaryWriter?.Dispose();
 }