////////////////////////////////////////////////////////////////
 //    OPEN SOURCE CODE
 //    Based on the Utf8Checker class found here: http://utf8checker.codeplex.com/
 ////////////////////////////////////////////////////////////////
 private static bool checkUTFWithoutBOM(string PhysicalPath)
 {
     BufferedStream fstream = new BufferedStream(File.OpenRead(PhysicalPath));
     bool res = IsUtf8(fstream);
     fstream.Close();
     return res;
 }
Exemple #2
0
        static void Main(string[] args)
        {
            string remoteName = Environment.MachineName;

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            clientSocket.Connect(new IPEndPoint(Dns.GetHostEntry(remoteName).AddressList[0], 1800));

            Console.WriteLine("Client is connected.\n");

            using (Stream netStream = new NetworkStream(clientSocket, true), 
                bufStream = new BufferedStream(netStream, streamBufferSize))
            {
                Console.WriteLine("NetworkStream {0} seeking.\n", bufStream.CanSeek ? "supports" : "does not support");

                if (bufStream.CanWrite)
                {
                    SendData(netStream, bufStream);
                }

                if (bufStream.CanRead)
                {
                    ReceiveData(netStream, bufStream);
                }

                Console.WriteLine("\nShutting down the connection.");

                bufStream.Close();
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            FileStream fs1 = new FileStream("out.bin",FileMode.Create,FileAccess.Write,FileShare.Read);
            FileStream fs2 = new FileStream("out2.bin",FileMode.Create,FileAccess.Write,FileShare.Read);
            bf1 = new BufferedStream(fs1);
            bf2 = new BufferedStream(fs2);
            try
            {
                Server server = new Server(10, 4096* 100 * 2);
                server.Sequential = false;
                server.Start(new IPEndPoint(IPAddress.Any, 40004));
                server.MessageReceived += OnMessageReceived;

                server.ClientConnected += OnClientConnected;
                server.ClientDisconnected += OnClientDisconnected;
                Console.ReadKey();
            }
            finally
            {
                bf1.Flush();
                bf2.Flush();
                bf1.Close();
                bf2.Close();
                fs1.Close();
                fs2.Close();
            }
        }
Exemple #4
0
 public void avi_close()
 {
     if (fd != null)
     {
         fd.Close();
     }
 }
Exemple #5
0
        /* Unzips dirName + ".zip" --> dirName, removing dirName
         * first */
        public virtual void  Unzip(System.String zipName, System.String destDirName)
        {
#if SHARP_ZIP_LIB
            // get zip input stream
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zipFile;
            zipFile = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(System.IO.File.OpenRead(zipName + ".zip"));

            // get dest directory name
            System.String      dirName = FullDir(destDirName);
            System.IO.FileInfo fileDir = new System.IO.FileInfo(dirName);

            // clean up old directory (if there) and create new directory
            RmDir(fileDir.FullName);
            System.IO.Directory.CreateDirectory(fileDir.FullName);

            // copy file entries from zip stream to directory
            ICSharpCode.SharpZipLib.Zip.ZipEntry entry;
            while ((entry = zipFile.GetNextEntry()) != null)
            {
                System.IO.Stream streamout = new System.IO.BufferedStream(new System.IO.FileStream(new System.IO.FileInfo(System.IO.Path.Combine(fileDir.FullName, entry.Name)).FullName, System.IO.FileMode.Create));
                byte[]           buffer    = new byte[8192];
                int len;
                while ((len = zipFile.Read(buffer, 0, buffer.Length)) > 0)
                {
                    streamout.Write(buffer, 0, len);
                }

                streamout.Close();
            }

            zipFile.Close();
#else
            Assert.Fail("Needs integration with SharpZipLib");
#endif
        }
Exemple #6
0
 private void button3_Click(object sender, EventArgs e)
 {
     try
     {
         string str1 = textBox1.Text;
         string str2 = textBox2.Text + "\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - textBox1.Text.LastIndexOf("\\") - 1);
         Stream myStream1, myStream2;
         BufferedStream myBStream1, myBStream2;
         byte[] myByte = new byte[1024];
         int i;
         myStream1 = File.OpenRead(str1);
         myStream2 = File.OpenWrite(str2);
         myBStream1 = new BufferedStream(myStream1);
         myBStream2 = new BufferedStream(myStream2);
         i = myBStream1.Read(myByte, 0, 1024);
         while (i > 0)
         {
             myBStream2.Write(myByte, 0, i);
             i = myBStream1.Read(myByte, 0, 1024);
         }
         myBStream2.Flush();
         myStream1.Close();
         myBStream2.Close();
         MessageBox.Show("文件复制完成");
     }
     catch(Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        public override void ShowUsage()
        {
            //BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。
            //为什么要封装其他流类,这么做的意义是什么?按照微软的话说主要是减少某些流直接操作存储设备的时间。
            //对于一些流来说直接向磁盘中存储数据这种做法的效率并不高,用BufferedStream包装过的流,先在内存中进行统一的处理再向磁盘中写入数据,也会提高写入的效率。

            Console.WriteLine("BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。");
            FileStream fileStream1 = File.Open(@"C:\NewText.txt", FileMode.OpenOrCreate, FileAccess.Read);  //读取文件流
            FileStream fileStream2 = File.Open(@"C:\Text2.txt", FileMode.OpenOrCreate, FileAccess.Write);   //写入文件流

            byte[] array4 = new byte[4096];

            BufferedStream bufferedInput = new BufferedStream(fileStream1);         //封装文件流
            BufferedStream bufferedOutput = new BufferedStream(fileStream2);        //封装文件流

            int byteRead = bufferedInput.Read(array4, 0, array4.Length);
            bufferedOutput.Write(array4, 0, array4.Length);

            //= bufferedInput.Read(array4, 0, 4096);
            while (byteRead > 0)                                                    //读取到了数据
            {
                bufferedOutput.Write(array4, 0, byteRead);
                Console.WriteLine(byteRead);
                break;
            };
            bufferedInput.Close();
            bufferedOutput.Close();
            fileStream1.Close();
            fileStream2.Close();
            Console.ReadKey();
        }
Exemple #8
0
 public void avi_close()
 {
     if (fd != null)
     {
         avi_idx1();
         fd.Close();
     }
 }
 public void Buffered_Stream_Closes_Output_On_Close()
 {
     var mock = new Mock<Stream>();
     Stream stream= mock.Object;
     mock.Setup(s => s.CanRead).Returns(true);
     BufferedStream bs = new BufferedStream(stream);
     bs.Close();
     mock.Verify(s=>s.Close());
 }
        public void Buffered_Stream_Rethrows_Exceptions_From_Underlying_Stream()
        {
            var mock = new Mock<Stream>();
            Stream stream = mock.Object;
            mock.SetupGet(d => d.CanRead).Returns(true);
            mock.Setup(d=>d.Close()).Throws(new IOException());

            BufferedStream bs = new BufferedStream(stream);
            bs.Close();
        }
Exemple #11
0
 public void avi_close()
 {
     if (fd != null)
     {
         avi_end(width, height, targetfps);
         writeindexs();
         fd.Close();
         fd.Dispose();
     }
     fd = null;
 }
Exemple #12
0
        static void Main(string[] args)
        {
            string fileName = "test2";
            //StreamReader sr = new StreamReader(fileName + ".vex", Encoding.ASCII);
            FileStream fs = new FileStream(fileName + ".vex", FileMode.Open, FileAccess.Read);
            BufferedStream bs = new BufferedStream(fs);
            JsonLexer lx = new JsonLexer(bs);
            List<Token> tokens = lx.Lex();
            fs.Close();
            bs.Close();
               // Document doc = JavaScriptConvert.DeserializeObject<Document>(json);
            Debug.WriteLine(tokens);

            //var g = from s in doc.Library.Items
            //        from l in s.Timeline.Layers
            //        select
            //            new
            //            {
            //                Name = s.Timeline.Name,
            //                Frames =
            //                    from f in l.Frames
            //                    where f.StartFrame == f.FrameIndex
            //                    select f
            //            };
            //try
            //{
            //    foreach (var tl in g)
            //    {
            //        foreach (var e in tl.Frames)
            //        {
            //            if (e != null)
            //            {
            //                Debug.WriteLine("tl: " + tl.Name + " \tl:" + e.LayerIndex + " f:" + e.FrameIndex + " \tsf:" + e.StartFrame);
            //            }
            //        }
            //    }
            //}
            //catch(Exception)
            //{
            //}

            //SwfCompilationUnit scu;
            //VexObject v;
            //Debug.WriteLine(Convert(fileName + ".swf", out scu, out v));
            //var tags = from ts in scu.Tags
            //        where ts.TagType == TagType.DefineSprite
            //        select (DefineSpriteTag)ts;

            //foreach (var t in tags)
            //{
            //    Debug.WriteLine(t.SpriteId + " t: " + t.FrameCount);
            //}
        }
Exemple #13
0
        public void putFile()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("这个请求是一个普通文件");
            Console.ResetColor();

            outputStream.WriteLine("HTTP/1.0 200 OK");
            outputStream.WriteLine("Content-Type: application/octet-stream");
            outputStream.WriteLine("Content-Disposition: attachment");
            outputStream.WriteLine("Connection: close");
            outputStream.WriteLine("");
            outputStream.Flush();

            FileStream stream = new FileStream(http_url_ondisk, FileMode.Open, FileAccess.Read);

            try
            {
                byte[] buff2 = new byte[1024];
                int    count = 0;
                while ((count = stream.Read(buff2, 0, 1024)) != 0)
                {
                    outputByteStream.Write(buff2, 0, count);
                }
                outputByteStream.Flush();
                outputByteStream.Close();
                stream.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("停止传输文件");
                stream.Close();
                outputByteStream.Close();
            }
        }
Exemple #14
0
        public void doReceive(Socket socket)
        {
            Console.WriteLine("输入存储路径");
           string filesPath= @Console.ReadLine();
            NetworkStream nsw = null;
            BufferedStream bsw = null;
            NetworkStream nsr = null;
            BufferedStream bsr = null;

            try
            {
                nsw = new NetworkStream(socket);
                bsw = new BufferedStream(nsw);
                nsr = new NetworkStream(socket);
                bsr = new BufferedStream(nsr);

                Console.WriteLine("************开始接收XML文件**************");
                receiveFile(xmlPath, bsr);
                Console.WriteLine("************成功接收XML文件**************");

                readXML(filesPath, bsr);

            }
            catch (Exception e) { }
            finally
            {
                if (bsw != null)
                {
                    bsw.Close();
                    bsw = null;
                }
                if (nsw != null)
                {
                    nsw.Close();
                    nsw = null;

                }


                if (bsr != null)
                {
                    bsr.Close();
                    bsr = null;
                }
                if (nsr != null)
                {
                    nsr.Close();
                    nsr = null;

                }
            }
        }
Exemple #15
0
        public Dataset Load(FileInfo file)
        {
            Stream ins = null;
            DcmParser parser = null;
            Dataset ds = null;

            try
            {
                try
                {
                    ins = new BufferedStream(new FileStream(file.FullName, FileMode.Open, FileAccess.Read));
                    parser = new DcmParser(ins);
                    FileFormat format = parser.DetectFileFormat();
                    if (format != null)
                    {
                        ds = new Dataset();
                        parser.DcmHandler = ds.DcmHandler;
                        parser.ParseDcmFile(format, Tags.PixelData);

                        //MessageBox.Show("Pomyślnie!");

                        return ds;
                    }
                    else
                    {
                        //MessageBox.Show("failed!");
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.StackTrace);
                }
            }
            finally
            {
                if (ins != null)
                {
                    try
                    {
                        ins.Close();
                    }
                    catch (IOException)
                    {
                    }
                }
            }

            return null;
        }
        /// <summary>
        /// Work around a 64Mb limit when writing streams to files.
        /// <seealso cref="http://groups.google.co.uk/group/microsoft.public.dotnet.framework/browse_thread/thread/ba3582b0a6e45517/03e8d3c8718a9c44"/>
        /// </summary>
        public static void WriteMemoryStreamToFile(string filename, MemoryStream memory)
        {
            //// old code:
            //using (Stream
            //    file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite),
            //    fileBuffer = new BufferedStream(file)
            //)
            //{
            //    byte[] memoryBuffer = memory.GetBuffer();
            //    int memoryLength = (int)memory.Length;
            //    fileBuffer.Write(memoryBuffer, 0, memoryLength); //##jpl: drawback: works only up to 2 gigabyte!
            //    fileBuffer.Close();
            //    file.Close();
            //}

            using (System.IO.Stream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                using (Stream buffer = new System.IO.BufferedStream(file))
                {
                    byte[] memoryBuffer = memory.GetBuffer();
                    long   memoryLength = memory.Length;
                    int    index        = 0;
                    // writing everything at once fails for writing memory streams larger than 64 megabyte
                    // to a file stream on the network
                    //buffer.Write(memoryBuffer, 0, memoryLength);
                    // so we introduce a temporary buffer
                    const int copyBufferSize = 65536;
                    byte[]    copyBuffer     = new byte[copyBufferSize];
                    while (memoryLength > 0)
                    {
                        int actualLength;
                        if (memoryLength > copyBufferSize)
                        {
                            actualLength = copyBufferSize;
                        }
                        else
                        {
                            actualLength = (int)memoryLength; //jpl: this cast is valid, as now memoryLength <= copyBufferSize
                        }
                        Array.Copy(memoryBuffer, index, copyBuffer, 0, actualLength);
                        buffer.Write(copyBuffer, 0, actualLength);
                        memoryLength = memoryLength - actualLength;
                        index        = index + actualLength;
                    }
                    buffer.Flush();
                    buffer.Close();
                }
            }
        }
Exemple #17
0
 public DumpResource(String baseDirectory, String resourceName, String cultureName)
 {
     // We are only interested in the messages belonging to the locale
       // itself, not in the inherited messages. Therefore we instantiate just
       // the GettextResourceSet, not a GettextResourceManager.
       Assembly satelliteAssembly =
     GetSatelliteAssembly(baseDirectory, resourceName, cultureName);
       GettextResourceSet catalog =
     InstantiateResourceSet(satelliteAssembly, resourceName, cultureName);
       BufferedStream stream = new BufferedStream(Console.OpenStandardOutput());
       Out = new StreamWriter(stream, new UTF8Encoding());
       Dump(catalog);
       Out.Close();
       stream.Close();
 }
 // Read all msgid/msgstr pairs (each string being NUL-terminated and
 // UTF-8 encoded) and write the .resources file to the given filename.
 WriteResource(String filename)
 {
     Stream input = new BufferedStream(Console.OpenStandardInput());
       reader = new StreamReader(input, new UTF8Encoding());
       if (filename.Equals("-")) {
     BufferedStream output = new BufferedStream(Console.OpenStandardOutput());
     // A temporary output stream is needed because ResourceWriter.Generate
     // expects to be able to seek in the Stream.
     MemoryStream tmpoutput = new MemoryStream();
     ResourceWriter rw = new ResourceWriter(tmpoutput);
     ReadAllInput(rw);
     #if __CSCC__
     // Use the ResourceReader to check against pnet-0.6.0 ResourceWriter
     // bug.
     try {
       ResourceReader rr = new ResourceReader(new MemoryStream(tmpoutput.ToArray()));
       foreach (System.Collections.DictionaryEntry entry in rr);
     } catch (IOException e) {
       throw new Exception("class ResourceWriter is buggy", e);
     }
     #endif
     tmpoutput.WriteTo(output);
     rw.Close();
     output.Close();
       } else {
     #if __CSCC__
     MemoryStream tmpoutput = new MemoryStream();
     ResourceWriter rw = new ResourceWriter(tmpoutput);
     ReadAllInput(rw);
     // Use the ResourceReader to check against pnet-0.6.0 ResourceWriter
     // bug.
     try {
       ResourceReader rr = new ResourceReader(new MemoryStream(tmpoutput.ToArray()));
       foreach (System.Collections.DictionaryEntry entry in rr);
     } catch (IOException e) {
       throw new Exception("class ResourceWriter is buggy", e);
     }
     BufferedStream output = new BufferedStream(new FileStream(filename, FileMode.Create, FileAccess.Write));
     tmpoutput.WriteTo(output);
     rw.Close();
     output.Close();
     #else
     ResourceWriter rw = new ResourceWriter(filename);
     ReadAllInput(rw);
     rw.Close();
     #endif
       }
 }
Exemple #19
0
        //-------------------------------------------------------------------------------------------
        /// <summary>
        /// This method generates a PDF copy of the check to be printed on standard 3 sheet check paper.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="invoice"></param>
        /// <returns>Returns the path to the PDF file on the local file system.</returns>
        public string GeneratePDF()
        {
            string filepath = System.IO.Path.GetTempFileName() + ".pdf";

               FileStream fos = new FileStream(filepath, FileMode.Create);
               BufferedStream bos = new BufferedStream(fos);
               PDF pdf = new PDF(bos);
               Page p = new PDFjet.NET.Page(pdf, Letter.PORTRAIT);

               // these two variables are lazy loaded from the db so we cache them here
               Logistics_Addresses payeeAddress = PayeeAddress;
               string payeeName = PayeeName;
               for (int i = 0; i < 3; i++)
               {
                    int yoffset = i * 251;
                    // these lines draw a seperation line between the 3 parts on a full check sheet which is useful for debugging
                    //Line l = new Line(0, yoffset, 400, yoffset);
                    //l.DrawOn(p);
                    //yoffset += 25;
                    // draw the date
                    DrawText(pdf, p, PostAt.ToString("MM/dd/yy"), 515, yoffset + 70);

                    int xnameoffset = (i == 0) ? 85 : 30;
                    DrawText(pdf, p, payeeName, xnameoffset, yoffset + 105);
                    DrawText(pdf, p, "**" + String.Format("{0:f}", Amount), 500, yoffset + 107);
                    int amountnodecimals = Convert.ToInt32(Math.Truncate(Amount));
                    int decimals = Convert.ToInt32((Amount - amountnodecimals) * 100);
                    DrawText(pdf, p, NumberConvertor.NumberToText(amountnodecimals).ToLower() + " dollar(s) " + NumberConvertor.NumberToText(decimals).ToLower() + " cents *****************", 30, yoffset + 130);

                    // draw the mailing address for windowed envelopes
                    string mailingAddress = (payeeAddress == null) ? "" : payeeAddress.ToString();
                    if (!String.IsNullOrEmpty(mailingAddress))
                    {
                         string[] addressLines = Regex.Split(mailingAddress, "\r\n");
                         for (int a = 0; a < addressLines.Length; a++)
                         {
                              DrawText(pdf, p, addressLines[a], 50, yoffset + 155 + (a * 12));
                         }
                    }

                    // draw the memo
                    DrawText(pdf, p, Memo, 30, yoffset + 215);
               }
               pdf.Flush();
               bos.Close();

               return filepath;
        }
        public void Buffered_Stream_buffers_and_forwards_writes_and_flushes_before_close()
        {
            var mock = new Mock<Stream>();
            Stream stream = mock.Object;
            mock.SetupGet(d => d.CanRead).Returns(true);
            mock.SetupGet(d => d.CanWrite).Returns(true);

            BufferedStream bs = new BufferedStream(stream);
            bs.WriteByte((byte)'a');
            bs.Flush();
            bs.Close();

            mock.Verify(d => d.Write(It.Is<byte[]>(array => array.Length > 0 && array[0] == 'a'), 0, 1));
            mock.Verify(d => d.Flush());
            mock.Verify(d => d.Close());
        }
Exemple #21
0
 public static void Compress(Stream instream, Stream outstream, int blockSize)
 {
     BufferedStream inStream = new BufferedStream(outstream);
     inStream.WriteByte(0x42);
     inStream.WriteByte(90);
     BufferedStream stream2 = new BufferedStream(instream);
     int num = stream2.ReadByte();
     BZip2OutputStream stream3 = new BZip2OutputStream(inStream);
     while (num != -1)
     {
         stream3.WriteByte((byte) num);
         num = stream2.ReadByte();
     }
     stream2.Close();
     stream3.Close();
 }
        public void TestGenerateKey()
        {
            PgpKeyRingGenerator krgen = CreateKeyRingGenerator(_dummyIdentity, _dummyKeyPassword);

            // Generate public key ring, dump to file.
            PgpPublicKeyRing pkr = krgen.GeneratePublicKeyRing();
            BufferedStream pubout = new BufferedStream(new FileStream(@"c:\temp\pgp\dummy2.asc", System.IO.FileMode.Create));
            pkr.Encode(pubout);
            pubout.Close();

            // Generate private key, dump to file.
            PgpSecretKeyRing skr = krgen.GenerateSecretKeyRing();
            BufferedStream secout = new BufferedStream(new FileStream(@"c:\temp\pgp\dummyprivate2.asc", System.IO.FileMode.Create));
            skr.Encode(secout);
            secout.Close();

        }
Exemple #23
0
        static void Main(string[] args)
        {
            // Check that an argument was specified when the
            // program was invoked.
            if (args.Length == 0)
            {
                Console.WriteLine("Error: The name of the host computer" +
                    " must be specified when the program is invoked.");
                return;
            }

            string remoteName = args[0];

            // Create the underlying socket and connect to the server.
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            clientSocket.Connect(new IPEndPoint(Dns.GetHostEntry(remoteName).AddressList[0], 1800));

            Console.WriteLine("Client is connected.\n");

            // Create a NetworkStream that owns clientSocket and
            // then create a BufferedStream on top of the NetworkStream.
            // Both streams are disposed when execution exits the
            // using statement.
            using (Stream netStream = new NetworkStream(clientSocket, true), bufStream = new BufferedStream(netStream, streamBufferSize))
            {
                // Check whether the underlying stream supports seeking.
                Console.WriteLine("NetworkStream {0} seeking.\n", bufStream.CanSeek ? "supports" : "does not support");

                // Send and receive data.
                if (bufStream.CanWrite)
                {
                    SendData(netStream, bufStream);
                }
                if (bufStream.CanRead)
                {
                    ReceiveData(netStream, bufStream);
                }

                // When bufStream is closed, netStream is in turn
                // closed, which in turn shuts down the connection
                // and closes clientSocket.
                Console.WriteLine("\nShutting down the connection.");
                bufStream.Close();
            }
        }
Exemple #24
0
//		internal McdFile(string basename, string directory)
//		{
//			BufferedStream file = new BufferedStream(File.OpenRead(directory+basename+".MCD"));
//			int diff = 0;
//			if(basename == "XBASES05")
//				diff=3;
//			tiles = new Tile[(file.Length/62)-diff];
//			PckFile f = GameInfo.GetPckFile(basename,directory,2);
//			for(int i=0;i<tiles.Length;i++)
//			{
//				byte[] info = new byte[62];
//				file.Read(info,0,62);
//				tiles[i] = new Tile(i,f,new McdEntry(info),this);
//			}
//
//			foreach(Tile t in tiles)
//				t.Tiles = tiles;
//			file.Close();
//		}

		internal McdFile(string basename, string directory, PckFile f)
		{
			BufferedStream file = new BufferedStream(File.OpenRead(directory+basename+".MCD"));
			int diff = 0;
			if(basename == "XBASES05")
				diff=3;
			tiles = new XCTile[(((int)file.Length)/62)-diff];
	
			for(int i=0;i<tiles.Length;i++)
			{
				byte[] info = new byte[62];
				file.Read(info,0,62); 
				tiles[i] = new XCTile(i,f,new McdEntry(info),this);
			}

			foreach(XCTile t in tiles)
				t.Tiles = tiles;
			file.Close();
		}
Exemple #25
0
        public void FetchFileFromServer()
        {
            TcpClient client = new TcpClient(hostName, port);
            if (client.Connected)
            {

                NetworkStream netStream = client.GetStream();

                try
                {

                    BufferedStream s_in = new BufferedStream(netStream);
                    byte[] buffer = new byte[8192];
                    int bytesRead;

                    string filePath = folderPath + requestedFile + ".mp3";
                    Stream s_out = File.OpenWrite(filePath);
                    while ((bytesRead = s_in.Read(buffer, 0, 8192)) > 0)
                    {
                        s_out.Write(buffer, 0, bytesRead);
                    }
                    s_out.Flush();
                    s_in.Close();
                    s_out.Close();
                    if (File.Exists(filePath))
                    {

                        Song song = new Song(filePath);
                        string artist = song.Artist;
                        string title = song.Title;
                        requestedFilePath=folderPath+artist+"-"+title+".mp3";
                        File.Move(filePath,requestedFilePath);
                    }
                }
                catch (Exception ex)
                {

                }

            }
        }
Exemple #26
0
        static void Main(string[] args)
        {
            FileStream fs = new FileStream("Hoo.txt",
                FileMode.Create, FileAccess.ReadWrite);

            BufferedStream bs = new BufferedStream(fs);
            Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position);

            for (int i = 0; i < 64; i++)
            {
                bs.WriteByte((byte)i);
            }

            Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position);

            Console.WriteLine("\nContents:");
            byte[] ba = new byte[bs.Length];
            bs.Position = 0;
            bs.Read(ba, 0, (int)bs.Length);
            foreach (byte b in ba)
            {
                Console.Write("{0, -3}", b);
            }

            string s = "Foo";
            for (int i = 0; i < 3; i++)
            {
                bs.WriteByte((byte)s[i]);
            }

            Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position);
            for (int i = 0; i < (256-67) + 1; i++)
            {
                bs.WriteByte((byte)i);
            }

            Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position);

            bs.Close();
            Console.ReadLine();
        }
Exemple #27
0
        public static string PostRequest(string url, WebHeaderCollection headers)
        {
            var responseFromServer = "";
            ServicePointManager.Expect100Continue = false;
            WebProxy myProxy = new WebProxy();
            myProxy.IsBypassed(new Uri(url));
            var request = (HttpWebRequest) WebRequest.Create(url);
            request.Proxy = myProxy;
            request.Method = "POST";
            request.ContentType = "text/plain; charset=UTF-8";
            request.Referer = Parse.BET365_HOME + "/";
            request.Headers.Add("Origin", Parse.BET365_HOME);
            request.UserAgent = Parse.USER_AGENT;
            request.Accept = "*/*";
            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.KeepAlive = true;
            request.ContentLength = 0;
            request.Headers.Add(headers);
            request.Timeout = 1500;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var dataStream = response.GetResponseStream())
                {
                    Debug.Assert(dataStream != null, "dataStream != null");
                    using (BufferedStream buffer = new BufferedStream(dataStream))
                    {
                        using (StreamReader readerStream = new StreamReader(buffer))
                        {
                            responseFromServer = readerStream.ReadToEnd();
                            readerStream.Close();
                        }
                        buffer.Close();
                    }
                    response.Close();
                    dataStream.Close();

                }
            }
            return responseFromServer;
        }
        public void getQRCode()
        {
            string url_login = "******";
            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
            HttpResponseMessage response = httpClient.GetAsync(new Uri(url_login)).Result;
            HttpRequestMessage request = response.RequestMessage;
            if (response.StatusCode != HttpStatusCode.OK)
            {
                //异常,
            }
            SetCookies = response.Headers.GetValues("Set-Cookie");

            FileStream fs = new FileStream(dir + "code.png", FileMode.Create);       
            BufferedStream sw = new BufferedStream(fs,1024);
            byte[] imgdata = null;
            imgdata = response.Content.ReadAsByteArrayAsync().Result;
            //var data  =  response.Content.ReadAsByteArrayAsync().Result;
            sw.Write(imgdata,0, imgdata.Length);
            sw.Close();
            fs.Close();
        }
    public void ExportVirtualRegistryToFile(string RegFileName, RegistryKey key, String virtKey)
    {
      int rootKeyLen = key.Name.Length + 1;
      if (!String.IsNullOrEmpty(virtKey))
        key = key.OpenSubKey(virtKey);

      FileStream fs = new FileStream(RegFileName, FileMode.Create);
      BufferedStream bfs = new BufferedStream(fs);
      StreamWriter sw = new StreamWriter(bfs);

      sw.WriteLine("Windows Registry Editor Version 5.00");
      sw.WriteLine("");
      writeRegKeys(sw, rootKeyLen, key);

      sw.Close();
      bfs.Close();
      fs.Close();

      if (errors.Length > 0)
      {
        MessageBox.Show("The following errors occured while exporting the registry: "+errors);
      }
    }
			internal SignerInfo ToSignerInfo(
                DerObjectIdentifier	contentType,
                CmsProcessable		content,
				SecureRandom		random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
				string digestName = Helper.GetDigestAlgName(digestOID);

				string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
				ISigner sig = Helper.GetSignatureInstance(signatureName);

                byte[] hash;
                if (outer._digests.Contains(digestOID))
                {
                    hash = (byte[])outer._digests[digestOID];
                }
                else
                {
                    IDigest dig = Helper.GetDigestInstance(digestName);
                    if (content != null)
                    {
                        content.Write(new DigOutputStream(dig));
                    }
                    hash = DigestUtilities.DoFinal(dig);
                    outer._digests.Add(digestOID, hash.Clone());
                }

				sig.Init(true, new ParametersWithRandom(key, random));
#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
				Stream sigStr = new SigOutputStream(sig);
#else
				Stream sigStr = new BufferedStream(new SigOutputStream(sig));
#endif

				Asn1Set signedAttr = null;
				if (sAttr != null)
				{
					IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (contentType == null) //counter signature
                    {
                        if (signed != null && signed[CmsAttributes.ContentType] != null)
                        {
                            IDictionary tmpSigned = signed.ToDictionary();
                            tmpSigned.Remove(CmsAttributes.ContentType);
                            signed = new Asn1.Cms.AttributeTable(tmpSigned);
                        }
                    }

					// TODO Validate proposed signed attributes

					signedAttr = outer.GetAttributeSet(signed);

					// sig must be composed from the DER encoding.
					new DerOutputStream(sigStr).WriteObject(signedAttr);
				}
                else if (content != null)
                {
					// TODO Use raw signature of the hash value instead
					content.Write(sigStr);
                }

				sigStr.Close();
				byte[] sigBytes = sig.GenerateSignature();

				Asn1Set unsignedAttr = null;
				if (unsAttr != null)
				{
					IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
					baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

					// TODO Validate proposed unsigned attributes

					unsignedAttr = outer.GetAttributeSet(unsigned);
				}

				// TODO[RSAPSS] Need the ability to specify non-default parameters
				Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
				AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(
					new DerObjectIdentifier(encOID), sigX509Parameters);
				
                return new SignerInfo(signerIdentifier, digAlgId,
                    signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr);
            }
Exemple #31
0
    // ----------------- Dumping a .resources file ------------------

    public DumpResource (String filename) {
      BufferedStream stream = new BufferedStream(Console.OpenStandardOutput());
      Out = new StreamWriter(stream, new UTF8Encoding());
      ResourceReader rr;
      if (filename.Equals("-")) {
        BufferedStream input = new BufferedStream(Console.OpenStandardInput());
        // A temporary output stream is needed because ResourceReader expects
        // to be able to seek in the Stream.
        byte[] contents;
        {
          MemoryStream tmpstream = new MemoryStream();
          byte[] buf = new byte[1024];
          for (;;) {
            int n = input.Read(buf, 0, 1024);
            if (n == 0)
              break;
            tmpstream.Write(buf, 0, n);
          }
          contents = tmpstream.ToArray();
          tmpstream.Close();
        }
        MemoryStream tmpinput = new MemoryStream(contents);
        rr = new ResourceReader(tmpinput);
      } else {
        rr = new ResourceReader(filename);
      }
      foreach (DictionaryEntry entry in rr) // uses rr.GetEnumerator()
        DumpMessage(entry.Key as String, null, entry.Value as String);
      rr.Close();
      Out.Close();
      stream.Close();
    }
        public static IEnumerable<string> ReadFile(string path, string seekText = "")
        {
            FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BufferedStream bs = new BufferedStream(fs);
            StreamReader sr = new StreamReader(bs);

            string line = "";

            bool seekTextRequested = !string.IsNullOrEmpty(seekText);
            //bool seekTextFound = false;

            long seekTextFoundAtLine = -1;

            if (seekTextRequested)
            {
            long currentLine = 0;
            while (true)
            {
                ++currentLine;
                line = sr.ReadLine();

                if (line == null)
                {
                    break;
                }

                // if seekText not found yet, skip
                if (line.IndexOf(seekText) == -1)
                {
                    continue;
                }

                seekTextFoundAtLine = currentLine;

                //Debug.Log("seeking: " + line);
                //Debug.Log("seekText found at: " + currentLine);
            }
            //Debug.Log("done seeking");

            if (seekTextFoundAtLine != -1)
            {
                /*sr.Close();
                bs.Close();
                fs.Close();

                fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                //fs.Seek(positionOfLastSeekText, SeekOrigin.Begin);
                fs.Position = positionOfLastSeekText;
                bs = new BufferedStream(fs);
                sr = new StreamReader(bs);*/

                fs.Seek(0, SeekOrigin.Begin);

                currentLine = 0;
                while (true)
                {
                    ++currentLine;
                    line = sr.ReadLine();

                    if (line == null)
                    {
                        break;
                    }
                    if (currentLine < seekTextFoundAtLine)
                    {
                        continue;
                    }

                    //Debug.Log("seeked: " + line);

                    yield return line;
                }
            }
            }
            else
            {
            while (true)
            {
                line = sr.ReadLine();

                if (line == null)
                {
                    break;
                }

                yield return line;
            }
            }

            line = "";

            sr.Close();
            bs.Close();
            fs.Close();
        }
Exemple #33
0
        /**
       * Retrieves meta data contained in the file.
       */
        public Dictionary<string, string> getFileMetaData(string path)
        {

            Dictionary<String, String> keywords = new Dictionary<String, String>();
            FileInfo f = new FileInfo(path);
            if (f.Exists)
            {

                BufferedStream randomAccess = null;
                PdfReader pdfReader = null;
                try
                {
                    randomAccess = new BufferedStream(WaitForFile(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                    if (randomAccess.CanRead)
                    {
                        pdfReader = new PdfReader(randomAccess, null);
                        keywords = getFileMetaData(pdfReader);

                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                finally
                {
                    if (randomAccess != null)
                    {
                        randomAccess.Close();

                    }
                    if (pdfReader != null)
                    {
                        pdfReader.Close();
                        pdfReader.Dispose();
                        pdfReader = null;

                    }
                }
            }
            return keywords;
        }
Exemple #34
0
        /**
         * Internal function used to process folders in the dictionary. These values 
         * usually come from the property file. It retrieves the number of files contained, whether or not
         * the folder contains a new file.
         */
        private List<FolderInfo> processFolderList(Dictionary<string, string> folderList)
        {
            List<FolderInfo> toReturn = new List<FolderInfo>();
            Dictionary<String, String> keywords = null;
            JavaScriptSerializer j = new JavaScriptSerializer();
            SpiderWeb.Models.FolderInfo tempInfo;
            string dirName;
            PdfReader pdfReader = null;

            BufferedStream randomAccess = null;
            foreach (KeyValuePair<string, string> entry in folderList)
            {
                dirName = entry.Value;

                FileInfo tempFile = new FileInfo(dirName);
                tempInfo = new SpiderWeb.Models.FolderInfo();
                tempInfo.folderName = dirName.Substring(dirName.LastIndexOf("\\") + 1);
                tempInfo.folderPath = dirName;

                dirName = tempFile.FullName;
                if (!Directory.Exists(dirName) && (dirName.ToUpper().StartsWith(this.data["DRR_DRIVE"] + ":") || dirName.StartsWith("\\\\")))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (Directory.Exists(dirName))
                {
                    string[] allFiles = Directory.GetFiles(dirName, "*pdf");
                    tempInfo.fileCount = allFiles.Length;
                    tempInfo.hasNewFile = false;
                    string openDirectory, currentDirectory;
                    foreach (string fileName in allFiles)
                    {
                        try
                        {

                            randomAccess = new BufferedStream(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), 12288);
                            pdfReader = new PdfReader(randomAccess, null);

                            if (pdfReader.Info.ContainsKey("Keywords"))
                            {
                                keywords = j.Deserialize<Dictionary<String, String>>(getValue(pdfReader.Info, "Keywords"));
                                //keywords = getKeywords(output);
                                /*if (pdfDocument.Metadata != null && pdfDocument.Metadata["Keywords"] != null && pdfDocument.Metadata["Keywords"].ToString().Length > 0)
                                {
                                    keywords = j.Deserialize<Dictionary<String, String>>((string)pdfDocument.Metadata["Keywords"]);*/
                                openDirectory = getValue(keywords, IndividualRFileInfo.OPEN_DIRECTORY);
                                currentDirectory = getValue(keywords, IndividualRFileInfo.CURRENT_DIRECTORY);
                                if (openDirectory != currentDirectory || openDirectory.Length == 0)
                                {
                                    tempInfo.hasNewFile = true;
                                    break;
                                }
                            }
                            else
                            {
                                tempInfo.hasNewFile = true;
                                break;
                            }

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.StackTrace);
                        }
                        finally
                        {
                            randomAccess.Close();
                            pdfReader.Close();
                            pdfReader.Dispose();
                            pdfReader = null;

                        }
                    }

                    //  allFolders[dirName] = tempInfo;
                }
                dirName = dirName.Substring(dirName.LastIndexOf("\\") + 1);
                tempInfo.alias = entry.Key;

                toReturn.Add(tempInfo);
            }
            return toReturn;
        }
Exemple #35
0
        /**
        * Returns meta data information from the pdf file
        */
        public Dictionary<string, string> GetFileChartInformation(string path)
        {
            BufferedStream randomAccess = null;
            PdfReader pdfReader = null;

            Dictionary<String, String> keywords = new Dictionary<String, String>();
            JavaScriptSerializer j = new JavaScriptSerializer();
            try
            {
                //if (File.Exists(path))
                // {
                randomAccess = new BufferedStream(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                pdfReader = new PdfReader(randomAccess, null);


                keywords = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(getValue(pdfReader.Info, "Keywords"));

                //}
            }
            catch (Exception e)
            {
                ExceptionUtility.LogException(e, "");
            }
            finally
            {
                if (randomAccess != null)
                {
                    randomAccess.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                    pdfReader.Dispose();
                    pdfReader = null;
                }
            }
            return keywords;
        }
Exemple #36
0
        /**
       * Sets a single key value pair in the files metadata
       */
        public void setMetaData(string path, string key, string value)
        {
            Hashtable toReturn = new Hashtable();
            FileInfo f = new FileInfo(path);
            BufferedStream randomAccess = null;
            PdfReader pdfReader = null;
            Dictionary<String, String> keywords = new Dictionary<String, String>();
            JavaScriptSerializer j = new JavaScriptSerializer();
            try
            {
                // if (File.Exists(f.FullName))
                // {
                randomAccess = new BufferedStream(new FileStream(f.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
                pdfReader = new PdfReader(randomAccess, null);
                keywords = new JavaScriptSerializer().Deserialize<Dictionary<String, String>>(getValue(pdfReader.Info, "Keywords"));
                //  }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            finally
            {

            }
            if (keywords == null)
            {
                keywords = new Dictionary<String, String>();
            }
            if (pdfReader != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
                    {
                        Dictionary<String, String> info = pdfReader.Info;
                        if (keywords.ContainsKey(key))
                        {
                            keywords[key] = value;
                            if (key != IndividualRFileInfo.CURRENT_DIRECTORY)
                            {
                                FileInfo fInfo = new FileInfo(path);
                                if (keywords.ContainsKey(IndividualRFileInfo.CURRENT_DIRECTORY))
                                {
                                    keywords[IndividualRFileInfo.CURRENT_DIRECTORY] = fInfo.Directory.Name;
                                }
                                else
                                {
                                    keywords.Add(IndividualRFileInfo.CURRENT_DIRECTORY, fInfo.Directory.Name);

                                }
                            }
                        }
                        else
                        {
                            keywords.Add(key, value);
                        }
                        string allStr = j.Serialize(keywords);
                        info["Keywords"] = allStr;

                        stamper.MoreInfo = info;
                        stamper.Close();
                    }
                    if (randomAccess != null)
                    {
                        randomAccess.Close();

                    }
                    if (pdfReader != null)
                    {
                        pdfReader.Close();
                    }

                    //File.Delete(path);
                    File.WriteAllBytes(path, ms.ToArray());
                    ms.Close();
                    ms.Dispose();
                }

            }
        }
Exemple #37
0
        /// <summary>
        /// Compare a source file with multiple destination files
        /// </summary>
        /// <param name="sourceFile">Source file path</param>
        /// <param name="comparisonFiles">List of destination files.</param>
        /// <returns>The result of the comparison</returns>
        public ComparisonResult CompareFiles(String sourceFile, List <String> comparisonFiles)
        {
            List <DestinationInfo> files = new List <DestinationInfo>();

            comparisonFiles.ForEach(file => files.Add(new DestinationInfo(file)));

            if (!File.Exists(sourceFile))
            {
                files.ForEach(file =>
                {
                    file.Done   = true;
                    file.Result = new ComparisonResult.Destination(file.Path, ComparisonResult.DifferenceType.SourceMissing);
                });
                return(new ComparisonResult(sourceFile, files.Select(file => file.Result).ToList(), true));
            }

            List <ComparisonResult.Destination> results = new List <ComparisonResult.Destination>();
            // get file length and make sure lengths are identical
            long length = new System.IO.FileInfo(sourceFile).Length;

            foreach (DestinationInfo file in files.Where(file => !file.Done))
            {
                if (sourceFile == file.Path)
                {
                    file.Done   = true;
                    file.Result = new ComparisonResult.Destination(file.Path, ComparisonResult.DifferenceType.Equal);
                }
                else if (!File.Exists(file.Path))
                {
                    file.Done   = true;
                    file.Result = new ComparisonResult.Destination(file.Path, ComparisonResult.DifferenceType.DestMissing);
                }
                else if (length != new System.IO.FileInfo(file.Path).Length)
                {
                    file.Done   = true;
                    file.Result = new ComparisonResult.Destination(file.Path, ComparisonResult.DifferenceType.NotEqual);
                }
                else if (useFastCompareForFile(file.Path))
                {
                    file.Done   = true;
                    file.Result = new ComparisonResult.Destination(file.Path, ComparisonResult.DifferenceType.Equal);
                }
                if (file.Done)
                {
                    results.Add(file.Result);
                }
            }

            if (!files.All(f => f.Done))
            {
                System.IO.BufferedStream sourceStream = null;
                try
                {
                    sourceStream = new System.IO.BufferedStream(System.IO.File.OpenRead(sourceFile));
                    foreach (DestinationInfo file in files.Where(f => !f.Done))
                    {
                        file.BufferStream = new System.IO.BufferedStream(System.IO.File.OpenRead(file.Path));
                    }
                    results.AddRange(CompareStreams(sourceStream, files.Where(f => !f.Done)));
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); }
                finally
                {
                    if (sourceStream != null)
                    {
                        sourceStream.Close();
                    }
                    foreach (DestinationInfo file in files.Where(f => f.Buffer != null))
                    {
                        file.BufferStream.Close();
                    }
                    foreach (DestinationInfo file in files.Where(f => !f.Done))
                    {
                        file.Done = true;
                        results.Add(new ComparisonResult.Destination(file.Path, ComparisonResult.DifferenceType.Equal));
                    }
                }
            }
            return(new ComparisonResult(sourceFile, results, true));
        }