Close() public method

public Close ( ) : void
return void
 public void CloseStream(Stream stream)
 {
     if (stream != null)
     {
         stream.Close();
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Write data from form to output stream.
        /// </summary>
        /// <param name="stream">Output stream.</param>
        /// <param name="xForm">XForm with data.</param>
        public void WriteXFormToXmlFile(Stream stream, XForm xForm)
        {
            var settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;

            using (var writer = System.Xml.XmlWriter.Create(stream, settings))
            {
                writer.WriteStartElement(xForm.Root.Name);
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

                foreach (var xAttribute in xForm.Root.Attributes)
                {
                    writer.WriteAttributeString(xAttribute.Name, xAttribute.GetStringXmlValue());
                }

                foreach (var xElement in xForm.Root.Elements)
                {
                    xElement.WriteXml(writer);
                }

                foreach (var xContainer in xForm.Root.Containers)
                {
                    xContainer.WriteXml(writer);
                }

                writer.WriteEndElement();
            }

            stream.Close();
        }
Ejemplo n.º 3
0
 public Art(Stream input)
 {
     ImageData=new byte[input.Length];
     input.Read(ImageData, 0, ImageData.Length);
     input.Close();
     input.Dispose();
 }
Ejemplo n.º 4
0
        public static DataTable RenderFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex)
        {
            var workbook = new HSSFWorkbook(ExcelFileStream);
            var sheet = workbook.GetSheet(SheetName);

            var table = new DataTable();

            var headerRow = sheet.GetRow(HeaderRowIndex);
            int cellCount = headerRow.LastCellNum;

            for (int i = headerRow.FirstCellNum; i < cellCount; i++)
            {
                var column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }

            int rowCount = sheet.LastRowNum;

            for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++)
            {
                var row = sheet.GetRow(i);
                var dataRow = table.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                    dataRow[j] = row.GetCell(j).ToString();
            }

            ExcelFileStream.Close();
            workbook = null;
            sheet = null;
            return table;
        }
Ejemplo n.º 5
0
 public static string Get(Stream fs)
 {
     HashAlgorithm ha = HashAlgorithm.Create();
     byte[] bytes = ha.ComputeHash(fs);
     fs.Close();
     return ToHexString(bytes);
 }
        /// <summary>
        ///     Reads a generic Pokémon container from a Stream.
        ///     Those containers are the ones that starts with "GR", "MM", "AD" and so on...
        /// </summary>
        /// <param name="data">Stream with container data</param>
        /// <returns></returns>
        public static OContainer load(Stream data)
        {
            BinaryReader input = new BinaryReader(data);
            OContainer output = new OContainer();

            IOUtils.readString(input, 0, 2); //Magic
            ushort sectionCount = input.ReadUInt16();
            for (int i = 0; i < sectionCount; i++)
            {
                OContainer.fileEntry entry = new OContainer.fileEntry();

                data.Seek(4 + (i * 4), SeekOrigin.Begin);
                uint startOffset = input.ReadUInt32();
                uint endOffset = input.ReadUInt32();
                uint length = endOffset - startOffset;

                data.Seek(startOffset, SeekOrigin.Begin);
                byte[] buffer = new byte[length];
                input.Read(buffer, 0, (int)length);
                entry.data = buffer;

                output.content.Add(entry);
            }

            data.Close();

            return output;
        }
Ejemplo n.º 7
0
 private static void OpenAndAddToWordprocessingStream(Stream stream, string txt)
 {
     Document doc = new Document(stream);
     stream.Close();
     DocumentBuilder db = new DocumentBuilder(doc);
     db.Writeln(txt);
     doc.Save(FileName);
 }
Ejemplo n.º 8
0
 public bool Check(Stream stream, bool closeStream = false)
 {
     var buffer = new byte[5];
     stream.Read(buffer, 0, 5);
     if (closeStream)
         stream.Close();
     return Check(buffer, 5);
 }
Ejemplo n.º 9
0
 public byte[] ReadToEnd(string path)
 {
     Stream = new FileStream(path, FileMode.Open);
     var memoryStream = new MemoryStream();
     Stream.CopyTo(memoryStream);
     Stream.Close();
     return memoryStream.ToArray();
 }
Ejemplo n.º 10
0
        /// <summary>
        ///     Reads a DARC archive.
        /// </summary>
        /// <param name="data">Stream of the data</param>
        /// <returns>The container data</returns>
        public static OContainer load(Stream data)
        {
            OContainer output = new OContainer();
            BinaryReader input = new BinaryReader(data);

            string darcMagic = IOUtils.readStringWithLength(input, 4);
            ushort endian = input.ReadUInt16();
            ushort headerLength = input.ReadUInt16();
            uint version = input.ReadUInt32();
            uint fileSize = input.ReadUInt32();
            uint tableOffset = input.ReadUInt32();
            uint tableLength = input.ReadUInt32();
            uint dataOffset = input.ReadUInt32();

            data.Seek(tableOffset, SeekOrigin.Begin);
            fileEntry root = getEntry(input);
            int baseOffset = (int)data.Position;
            int namesOffset = (int)(tableOffset + root.length * 0xc);

            string currDir = null;
            for (int i = 0; i < root.length - 1; i++)
            {
                data.Seek(baseOffset + i * 0xc, SeekOrigin.Begin);

                fileEntry entry = getEntry(input);

                if ((entry.flags & 1) > 0)
                {
                    //Folder
                    int index = i;
                    currDir = null;
                    for (;;)
                    {
                        uint parentIndex = entry.offset;
                        currDir = getName(input, entry.nameOffset + namesOffset) + "/" + currDir;
                        if (parentIndex == 0 || parentIndex == index) break;
                        data.Seek(baseOffset + parentIndex * 0xc, SeekOrigin.Begin);
                        entry = getEntry(input);
                        index = (int)parentIndex;
                    }

                    continue;
                }

                data.Seek(entry.offset, SeekOrigin.Begin);
                byte[] buffer = new byte[entry.length];
                data.Read(buffer, 0, buffer.Length);

                OContainer.fileEntry file = new OContainer.fileEntry();
                file.name = currDir + getName(input, entry.nameOffset + namesOffset);
                file.data = buffer;

                output.content.Add(file);
            }

            data.Close();
            return output;
        }
        private Stream CorrectView(string virtualPath, Stream stream)
        {
            if (_viewFixer == null)
                return stream;

            var outStream = _viewFixer.CorrectView(virtualPath, stream);
            stream.Close();
            return outStream;
        }
Ejemplo n.º 12
0
 public void CleanTo(Stream strDest, List<ContentType> elementsToClean)
 {
     using (DocxDocumentProcessor dp = new DocxDocumentProcessor(m_data.AsStream(), elementsToClean))
     {
         dp.Output = strDest;
         dp.Process(DocumentProcessingActions.Clean);
         strDest.Close();
     }
 }
Ejemplo n.º 13
0
 public void CleanTo(Stream strDest)
 {
     using (DocxDocumentProcessor dp = new DocxDocumentProcessor(m_data.AsStream()))
     {
         dp.Output = strDest;
         dp.Process(DocumentProcessingActions.Clean);
         strDest.Close();
     }
 }
Ejemplo n.º 14
0
        public void Stop(bool force)
        {
            StopClients();

            try { requestStream?.Close(); } catch { }
            try { WebResponse?.Close(); } catch { }
            requestStream = null;
            WebResponse   = null;
        }
Ejemplo n.º 15
0
 public void SubirFichero(Stream fichero, string nombre, string contenedor = null)
 {
     ComprobarContenedor();
     var cliente = _cuenta.CreateCloudBlobClient();
     var cont = cliente.GetContainerReference(_contenedor);
     var blob = cont.GetBlockBlobReference(nombre);
     blob.UploadFromStream(fichero);
     fichero.Close();
 }
Ejemplo n.º 16
0
        public void SubirFichero(Stream fichero, string nombre, string contenedor = null)
        {
            ComprobarContenedor(contenedor);

            var cliente = _cuenta.CreateCloudBlobClient();
            var cont = cliente.GetContainerReference(_contenedor);
            var blob = cont.GetBlockBlobReference(nombre);
            blob.UploadFromStream(fichero); //podría hacerse upload de array binario, texto, etc
            fichero.Close();
        }
Ejemplo n.º 17
0
        /// <summary>
        ///     Loads a Fantasy Life ZTEX texture from a Stream.
        /// </summary>
        /// <param name="data">The Stream with the data</param>
        /// <returns>The list of textures</returns>
        public static List<RenderBase.OTexture> load(Stream data)
        {
            List<RenderBase.OTexture> textures = new List<RenderBase.OTexture>();

            BinaryReader input = new BinaryReader(data);

            string ztexMagic = IOUtils.readString(input, 0, 4);
            ushort textureCount = input.ReadUInt16();
            input.ReadUInt16();
            input.ReadUInt32();

            List<textureEntry> entries = new List<textureEntry>();
            for (int i = 0; i < textureCount; i++)
            {
                textureEntry entry = new textureEntry();

                entry.name = IOUtils.readString(input, (uint)(0xc + (i * 0x58)));
                data.Seek(0xc + (i * 0x58) + 0x40, SeekOrigin.Begin);

                input.ReadUInt32();
                entry.offset = input.ReadUInt32();
                input.ReadUInt32();
                entry.length = input.ReadUInt32();
                entry.width = input.ReadUInt16();
                entry.height = input.ReadUInt16();
                input.ReadByte();
                entry.format = input.ReadByte();
                input.ReadUInt16();

                entries.Add(entry);
            }

            foreach (textureEntry entry in entries)
            {
                data.Seek(entry.offset, SeekOrigin.Begin);
                byte[] buffer = new byte[entry.length];
                data.Read(buffer, 0, buffer.Length);

                Bitmap bmp = null;
                switch (entry.format)
                {
                    case 1: bmp = TextureCodec.decode(buffer, entry.width, entry.height, RenderBase.OTextureFormat.rgb565); break;
                    case 5: bmp = TextureCodec.decode(buffer, entry.width, entry.height, RenderBase.OTextureFormat.rgba4); break;
                    case 9: bmp = TextureCodec.decode(buffer, entry.width, entry.height, RenderBase.OTextureFormat.rgba8); break;
                    case 0x18: bmp = TextureCodec.decode(buffer, entry.width, entry.height, RenderBase.OTextureFormat.etc1); break;
                    case 0x19: bmp = TextureCodec.decode(buffer, entry.width, entry.height, RenderBase.OTextureFormat.etc1a4); break;
                }

                textures.Add(new RenderBase.OTexture(bmp, entry.name));
            }

            data.Close();

            return textures;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Loads the coverage.
        /// </summary>
        /// <param name="expected">The expected.</param>
        /// <param name="actual">The actual.</param>
        /// <returns></returns>
		public static Coverage LoadCoverage(Stream expected, Stream actual)
		{
			var coverage = (Coverage)Utilities.Serialization.FromXml(expected, typeof(Coverage));
			var actualcoverage = (Coverage)Utilities.Serialization.FromXml(actual, typeof(Coverage));
			
			expected.Close();
			actual.Close();

			SetMisses(coverage, actualcoverage);

			return coverage;
		}
Ejemplo n.º 19
0
 /// <summary>
 /// Convenience method to copy stuff from StreamReader to StreamWriter
 /// </summary>
 protected void CopyStream(Stream i, Stream o)
 {
     byte[] buf = new byte[1024];
     while (true)
     {
         int sz = i.Read(buf, 0, buf.Length);
         if (sz == 0) break;
         o.Write(buf, 0, sz);
         o.Flush();
     }
     i.Close();
     o.Close();
 }
Ejemplo n.º 20
0
        //接收线程
        public void receive()
        {
            filename = formm.filenamew[threadh];
            strUrl = formm.strurl;
            ns = null;
            nbytes = new byte[512];
            nreadsize = 0;

            Console.WriteLine("线程" + threadh.ToString() + "开始接收");
            if (!File.Exists(filename))
            {
                fs = new FileStream(filename, System.IO.FileMode.Create);
            }
            else
            {
                fs = File.OpenWrite(filename);
                DownLoadSize = fs.Length;
                formm.DownLoadtotal += DownLoadSize;
                formm.filestartw[threadh] += DownLoadSize;
                fs.Seek(DownLoadSize, SeekOrigin.Current);   //已经存在
            }
            if (!formm.threadw[threadh])
            {
                try
              {
                 request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                //接收的起始位置及接收的长度
                 request.AddRange(formm.filestartw[threadh], formm.filestartw[threadh] + formm.filesizew[threadh]-DownLoadSize);
                 ns = request.GetResponse().GetResponseStream();//获得接收流
                 nreadsize = ns.Read(nbytes, 0, 512);

                 while (nreadsize > 0)
                 {
                    fs.Write(nbytes, 0, nreadsize);
                    nreadsize = ns.Read(nbytes, 0, 512);
                    formm.DownLoadtotal += 512;
                     Console.WriteLine("线程" + threadh.ToString() + "正在接收" + formm.DownLoadSpeed.ToString() + "k/s___已经下了" + formm.DownLoadtotal.ToString() + "还剩下" + formm.LeftDownLoadTime.ToString() + "s" + "百分比" + formm.DownLoadPercentage.ToString());
                 }
                 fs.Close();
                 ns.Close();
              }
               catch (Exception er)
              {
                Console.WriteLine("123");
                fs.Close();
              }
            }

               Console.WriteLine("进程" + threadh.ToString() + "接收完毕!");
            formm.threadw[threadh] = true;
        }
Ejemplo n.º 21
0
        public static byte[] decompress(Stream data, uint decodedLength)
        {
            byte[] input = new byte[data.Length - data.Position];
            data.Read(input, 0, input.Length);
            data.Close();
            long inputOffset = 0;

            byte[] output = new byte[decodedLength];
            long outputOffset = 0;

            byte[] dictionary = new byte[4096];
            long dictionaryOffset = 4078;

            ushort mask = 0x80;
            byte header = 0;

            while (outputOffset < decodedLength)
            {
                if ((mask <<= 1) == 0x100)
                {
                    header = input[inputOffset++];
                    mask = 1;
                }

                if ((header & mask) > 0)
                {
                    if (outputOffset == output.Length) break;
                    output[outputOffset++] = input[inputOffset];
                    dictionary[dictionaryOffset] = input[inputOffset++];
                    dictionaryOffset = (dictionaryOffset + 1) & 0xfff;
                }
                else
                {
                    ushort value = (ushort)(input[inputOffset++] | (input[inputOffset++] << 8));
                    int length = ((value >> 8) & 0xf) + 3;
                    int position = ((value & 0xf000) >> 4) | (value & 0xff);

                    while (length > 0)
                    {
                        dictionary[dictionaryOffset] = dictionary[position];
                        output[outputOffset++] = dictionary[dictionaryOffset];
                        dictionaryOffset = (dictionaryOffset + 1) & 0xfff;
                        position = (position + 1) & 0xfff;
                        length--;
                    }
                }
            }

            return output;
        }
Ejemplo n.º 22
0
        public Stream Echo(Stream data)
        {
            MemoryStream dataStorage = new MemoryStream();
            byte[] byteArray = new byte[8192];
            int bytesRead = data.Read(byteArray, 0, 8192);
            while (bytesRead > 0)
            {
                dataStorage.Write(byteArray, 0, bytesRead);
                bytesRead = data.Read(byteArray, 0, 8192);
            }
            data.Close();
            dataStorage.Seek(0, SeekOrigin.Begin);

            return dataStorage;
        }
Ejemplo n.º 23
0
 public override Stream OpenForDirectUpdate(Stream stream)
 {
     if ((stream == null) || !stream.CanWrite)
     {
         Stream destination = new MemoryStream();
         if (stream != null)
         {
             stream.Position = 0L;
             StreamUtils.Copy(stream, destination, new byte[0x1000]);
             stream.Close();
         }
         return destination;
     }
     return stream;
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Writes data from the stream to the specified output stream.
        /// </summary>
        /// <param name="inputStream">The stream to read from.</param>
        /// <param name="outputStream">The stream to write to.</param>
        /// <param name="closeOutputStream">True if the output stream should be closed after all data from 
        /// the input stream has been written; otherwise false.</param>
        public static void WriteTo(this Stream inputStream, Stream outputStream, bool closeOutputStream = true)
        {
            Ensure.ArgumentNotNull(outputStream, "outputStream");

            byte[] buffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
            }

            if (closeOutputStream)
            {
                outputStream.Close();
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="origenalFileExtesion"></param>
        /// <param name="clientFileName"></param>
        public static void Down(Stream stream, string origenalFileExtesion, string clientFileName)
        {
            string fileContentType = ContentTypes.GetContentType(origenalFileExtesion);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(clientFileName, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AddHeader("Content-Length", stream.Length.ToString());
            HttpContext.Current.Response.ContentType = fileContentType;

            IOHelper.BlocklyCircularlyOperateStream(stream, FlushBytesToResponse);

            stream.Close();
            HttpContext.Current.Response.OutputStream.Close();
            HttpContext.Current.Response.End();//非常重要,没有这句的话,页面的HTML代码将会保存到文件中
            HttpContext.Current.Response.Close();
        }
Ejemplo n.º 26
0
        public int Upload(Stream data)
        {
            int size = 0;
            int bytesRead = 0;
            byte[] buffer = new byte[1024];

            // Read all the data from the stream
            do
            {
                bytesRead = data.Read(buffer, 0, buffer.Length);
                size += bytesRead;
            } while (bytesRead > 0);
            data.Close();

            return size;
        }
Ejemplo n.º 27
0
        public static byte[] decompress(Stream data, uint decodedLength)
        {
            byte[] input = new byte[data.Length - data.Position];
            data.Read(input, 0, input.Length);
            data.Close();
            long inputOffset = 0;

            byte[] output = new byte[decodedLength];
            long outputOffset = 0;

            ushort mask = 0;
            byte header = 0;

            while (outputOffset < decodedLength)
            {
                if ((mask >>= 1) == 0)
                {
                    header = input[inputOffset++];
                    mask = 0x80;
                }

                if ((header & mask) > 0)
                {
                    if (outputOffset == output.Length) break;
                    output[outputOffset++] = input[inputOffset++];
                }
                else
                {
                    byte byte1 = input[inputOffset++];
                    byte byte2 = input[inputOffset++];

                    int dist = ((byte1 & 0xF) << 8) | byte2;
                    int position = (int)outputOffset - (dist + 1);

                    int length = byte1 >> 4;
                    if (length == 0)
                        length = input[inputOffset++] + 0x12;
                    else
                        length += 2;

                    while (length-- > 0) output[outputOffset++] = output[position++];
                }
            }

            return output;
        }
        /// <summary>
        ///   Modify the view
        /// </summary>
        /// <param name="virtualPath"> Path to view </param>
        /// <param name="stream"> Stream containing the original view </param>
        /// <returns> Stream with modified contents </returns>
        public Stream CorrectView(string virtualPath, Stream stream)
        {
            var reader = new StreamReader(stream, Encoding.UTF8);
            var view = reader.ReadToEnd();
            stream.Close();
            var ourStream = new MemoryStream();
            var writer = new StreamWriter(ourStream, Encoding.UTF8);

            var modelString = "";
            var modelPos = view.IndexOf("@model");
            if (modelPos != -1)
            {
                writer.Write(view.Substring(0, modelPos));
                var modelEndPos = view.IndexOfAny(new[] {'\r', '\n'}, modelPos);
                modelString = view.Substring(modelPos, modelEndPos - modelPos);
                view = view.Remove(0, modelEndPos);
            }

            writer.WriteLine("@using System.Web.Mvc");
            writer.WriteLine("@using System.Web.Mvc.Ajax");
            writer.WriteLine("@using System.Web.Mvc.Html");
            writer.WriteLine("@using System.Web.Routing");

            var basePrefix = "@inherits " + WebViewPageClassName;

            if (virtualPath.ToLower().Contains("__viewstart"))
                writer.WriteLine("@inherits System.Web.WebPages.StartPage");
            else if (modelString == "@model object")
                writer.WriteLine(basePrefix + "<dynamic>");
            else if (!string.IsNullOrEmpty(modelString))
                writer.WriteLine(basePrefix + "<" + modelString.Substring(7) + ">");
            else
                writer.WriteLine(basePrefix);

            // partial views should not have a layout
            if (!string.IsNullOrEmpty(LayoutPath) && !virtualPath.Contains("/_"))
            {
                writer.WriteLine(string.Format("@{{ Layout = \"{0}\"; }}", LayoutPath));
            }
            writer.Write(view);
            writer.Flush();
            ourStream.Position = 0;
            return ourStream;
        }
Ejemplo n.º 29
0
        /// <summary>
        ///     Reads FPT0 containers from Dragon Quest VII.
        /// </summary>
        /// <param name="data">Stream with container data</param>
        /// <returns></returns>
        public static GenericContainer.OContainer load(Stream data)
        {
            BinaryReader input = new BinaryReader(data);
            GenericContainer.OContainer output = new GenericContainer.OContainer();

            output.fileIdentifier = IOUtils.readString(input, 0, 4); //FPT0 magic
            input.ReadUInt32();
            uint entries = input.ReadUInt32();
            uint baseAddress = 0x10 + (entries * 0x20) + 0x80;
            input.ReadUInt32();

            List<sectionEntry> files = new List<sectionEntry>();
            for (int i = 0; i < entries; i++)
            {
                sectionEntry entry = new sectionEntry();

                entry.name = IOUtils.readString(input, (uint)(0x10 + (i * 0x20)));
                data.Seek(0x20 + (i * 0x20), SeekOrigin.Begin);
                input.ReadUInt32(); //Memory address?
                entry.offset = input.ReadUInt32() + baseAddress;
                entry.length = input.ReadUInt32();
                input.ReadUInt32(); //Padding?

                files.Add(entry);
            }

            foreach (sectionEntry file in files)
            {
                GenericContainer.OContainerEntry entry = new GenericContainer.OContainerEntry();

                data.Seek(file.offset, SeekOrigin.Begin);
                byte[] buffer = new byte[file.length];
                input.Read(buffer, 0, buffer.Length);
                entry.data = buffer;
                entry.name = file.name;

                output.content.Add(entry);
            }

            data.Close();

            return output;
        }
Ejemplo n.º 30
0
        /// <summary>
        ///     Reads a SARC archive.
        /// </summary>
        /// <param name="data">Stream of the data</param>
        /// <returns>The container data</returns>
        public static OContainer load(Stream data)
        {
            OContainer output = new OContainer();
            BinaryReader input = new BinaryReader(data);

            string sarcMagic = IOUtils.readStringWithLength(input, 4);
            ushort sarcHeaderLength = input.ReadUInt16();
            ushort endian = input.ReadUInt16();
            uint fileLength = input.ReadUInt32();
            uint dataOffset = input.ReadUInt32();
            uint dataPadding = input.ReadUInt32();

            string sfatMagic = IOUtils.readStringWithLength(input, 4);
            ushort sfatHeaderLength = input.ReadUInt16();
            ushort entries = input.ReadUInt16();
            uint hashMultiplier = input.ReadUInt32();
            int sfntOffset = 0x20 + entries * 0x10 + 8;

            for (int i = 0; i < entries; i++)
            {
                data.Seek(0x20 + i * 0x10, SeekOrigin.Begin);

                uint nameHash = input.ReadUInt32();
                uint nameOffset = (input.ReadUInt32() & 0xffffff) << 2;
                uint offset = input.ReadUInt32();
                uint length = input.ReadUInt32() - offset;

                string name = IOUtils.readString(input, (uint)(sfntOffset + nameOffset));
                data.Seek(offset + dataOffset, SeekOrigin.Begin);
                byte[] buffer = new byte[length];
                data.Read(buffer, 0, buffer.Length);
                if (name == "") name = string.Format("file_{0:D5}{1}", i, FileIO.getExtension(buffer));

                OContainer.fileEntry entry = new OContainer.fileEntry();
                entry.name = name;
                entry.data = buffer;
                output.content.Add(entry);
            }

            data.Close();
            return output;
        }
Ejemplo n.º 31
0
 //thanks to: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class
 public void upload(string remoteFile, string localFile)
 {
     ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
     ftpRequest.Credentials = new NetworkCredential(user, pass);
     ftpRequest.UseBinary = true;
     ftpRequest.UsePassive = true;
     ftpRequest.KeepAlive = true;
     ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
     ftpStream = ftpRequest.GetRequestStream();
     FileStream localFileStream = new FileStream(localFile, FileMode.Open);
     byte[] byteBuffer = new byte[bufferSize];
     int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
     while (bytesSent != 0)
     {
         ftpStream.Write(byteBuffer, 0, bytesSent);
         bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
     }
     localFileStream.Close();
     ftpStream.Close();
     ftpRequest = null;
 }
Ejemplo n.º 32
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Setea parametros y objetos del request
            //

            Uri            address = new Uri(@"http://10.240.8.15:8080/wsCloudera/webapi/grabaciones");
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

            request.Method      = "POST";
            request.ContentType = "application/json";

            //Instancia clase de objeto de la data que se enviara
            DataRequest drq = new DataRequest();

            drq.fechaDesde = "2017011200";
            drq.fechaHasta = "2017011210";
            drq.skill      = "SKILL_103EPH";
            drq.limit      = 10;
            drq.tableName  = "grabaciones";

            //Se parsea la data dejandola en string con estructura json
            string parseDRQ = JsonConvert.SerializeObject(drq);

            //Se manda a ejecutar el request
            byte[] bytes = Encoding.UTF8.GetBytes(parseDRQ);
            request.ContentLength = bytes.Length;
            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            //Se obtiene la respuesta
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                Console.WriteLine(reader.ReadToEnd());
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 从谷歌官方api获取发音并下载到本地,返回音频文件相对路径
        /// </summary>
        /// <param name="word">单词全拼</param>
        /// <returns>返回音频文件相对路径</returns>
        private static string makeMp3(string word)
        {
            try
            {
                string url  = "http://translate.google.com/translate_tts?tl=en&q=" + word;
                string k    = word.Substring(0, 1);
                string path = Directory.CreateDirectory("wordVolice/") + "\\" + k;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);//在根目录下建立文件夹
                }
                string filename = path + "\\" + word + ".mp3";


                System.Net.HttpWebRequest  Myrq      = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                System.Net.HttpWebResponse myrp      = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long             totalBytes          = myrp.ContentLength;
                System.IO.Stream st                  = myrp.GetResponseStream();
                System.IO.Stream so                  = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by                  = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                return("/wordVolice/" + k + "/" + word + ".mp3");
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 34
0
        public string HttpPostData(string url, string param)
        {
            var result = string.Empty;

            //注意提交的编码 这边是需要改变的 这边默认的是Default:系统当前编码
            byte[] postData = Encoding.UTF8.GetBytes(param);

            // 设置提交的相关参数
            HttpWebRequest request    = WebRequest.Create(url) as HttpWebRequest;
            Encoding       myEncoding = Encoding.UTF8;

            request.Method            = "POST";
            request.KeepAlive         = false;
            request.AllowAutoRedirect = true;
            request.ContentType       = "application/x-www-form-urlencoded";
            request.UserAgent         = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.ContentLength     = postData.Length;

            // 提交请求数据
            System.IO.Stream outputStream = request.GetRequestStream();
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();

            HttpWebResponse response;
            Stream          responseStream;
            StreamReader    reader;
            string          srcString;

            response       = request.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader         = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
            srcString      = reader.ReadToEnd();
            result         = srcString; //返回值赋值
            reader.Close();

            return(result);
        }
Ejemplo n.º 35
0
/*
 * -- off -> set cool permanent hold heat at 50
 * CoolNextPeriod: null
 * CoolSetpoint: null
 * DeviceID: 416280
 * FanMode: null
 * HeatNextPeriod: null
 * HeatSetpoint: 51
 * StatusCool: 2
 * StatusHeat: 2
 * SystemSwitch: 1
 *
 * --> off
 * CoolNextPeriod: null
 * CoolSetpoint: null
 * DeviceID: 416280
 * FanMode: null
 * HeatNextPeriod: null
 * HeatSetpoint: null
 * StatusCool: null
 * StatusHeat: null
 * SystemSwitch: 2
 *
 * --> heat hold until 8:15 pm
 * CoolNextPeriod: 81
 * CoolSetpoint: null
 * DeviceID: 416280
 * FanMode: null
 * HeatNextPeriod: 81
 * HeatSetpoint: 52
 * StatusCool: 1
 * StatusHeat: 1
 * SystemSwitch: 1
 *
 * --> follow schedule
 * CoolNextPeriod: null
 * CoolSetpoint: 99
 * DeviceID: 416280
 * FanMode: null
 * HeatNextPeriod: null
 * HeatSetpoint: 50
 * StatusCool: 0
 * StatusHeat: 0
 * SystemSwitch: null
 */

        /// <summary>
        /// Control the thermostat
        /// </summary>
        /// <param name="systemSwitch">Off, Heat, Cool</param>
        /// <param name="schedule">FollowSchedule, HoldUntil, PermanentHold</param>
        /// <param name="setPoint">Set poitn for heating or cooling</param>
        /// <param name="holdHour">Hours to hold for. E.g. 2 holds for 2 hours.</param>
        /// <param name="holdMinute">Minutes to hold for in multiples of 15 minutes. E.g. 2 = 30 minutes</param>
        public void Set(SystemSwitchEnum systemSwitch, ScheduleEnum schedule, int setPoint, int nextPeriod)
        {
            System.Net.HttpWebRequest  request;
            System.Net.HttpWebResponse response;
            StreamReader streamReader;
            String       responseString;

            request                 = (HttpWebRequest)System.Net.HttpWebRequest.Create("https://mytotalconnectcomfort.com/portal/Device/SubmitControlScreenChanges");
            request.KeepAlive       = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.CookieContainer = Account.Login();
            request.Method          = "POST";
            request.Accept          = "application/json, text/javascript, */*";
            request.ContentType     = "application/json; charset=UTF-8";
            request.UserAgent       = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36";
            string postData = "{ \"DeviceID\":" + ID;

            postData += ", \"CoolNextPeriod\":" + ((schedule == ScheduleEnum.HoldUntil) ? nextPeriod.ToString() : "null");
            postData += ", \"CoolSetPoint\":" + ((systemSwitch == SystemSwitchEnum.Cool) ? setPoint.ToString() : "null");
            postData += ", \"FanMode\":null";
            postData += ", \"HeatNextPeriod\":" + ((schedule == ScheduleEnum.HoldUntil) ? nextPeriod.ToString() : "null");
            postData += ", \"HeatSetPoint\":" + ((systemSwitch == SystemSwitchEnum.Heat) ? setPoint.ToString() : "null");
            postData += ", \"StatusCool\":" + (int)schedule;
            postData += ", \"StatusHeat\":" + (int)schedule;
            postData += ", \"SystemSwitch\":" + (int)systemSwitch;
            postData += "}";
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
            request.ContentLength = byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            response       = (HttpWebResponse)request.GetResponse();
            streamReader   = new StreamReader(response.GetResponseStream());
            responseString = streamReader.ReadToEnd();
            response.Close();
        }
Ejemplo n.º 36
0
        public string PFPost(string postData)
        {
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
            Encoding encoding = Encoding.UTF8;

            byte[] data = encoding.GetBytes(postData.Trim());
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);
            req.Method = "POST";
            //req.ContentType = "application/x-www-form-urlencoded";
            req.ContentType = "application/json";
            //req.ContentType = "text/html";

            req.ContentLength = data.Length;

            System.IO.Stream newStream = req.GetRequestStream();
            //发送数据
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            StreamReader reader            = new StreamReader(res.GetResponseStream(), Encoding.UTF8);

            return(reader.ReadToEnd());
        }
        private void GetBearerToken()
        {
            //https://dev.twitter.com/oauth/application-only
            //Step 1
            string strBearerRequest = HttpUtility.UrlEncode(_ConsumerKey) + ":" + HttpUtility.UrlEncode(_ConsumerSecret);

            strBearerRequest = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(strBearerRequest));

            //Step 2
            WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");

            request.Headers.Add("Authorization", "Basic " + strBearerRequest);
            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

            string strRequestContent = "grant_type=client_credentials";

            byte[]           bytearrayRequestContent = System.Text.Encoding.UTF8.GetBytes(strRequestContent);
            System.IO.Stream requestStream           = request.GetRequestStream();
            requestStream.Write(bytearrayRequestContent, 0, bytearrayRequestContent.Length);
            requestStream.Close();

            string responseJson = string.Empty;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                System.IO.Stream responseStream = response.GetResponseStream();
                responseJson = new StreamReader(responseStream).ReadToEnd();
            }

            JObject jobjectResponse = JObject.Parse(responseJson);

            _BearerToken = jobjectResponse["access_token"].ToString();
        }
Ejemplo n.º 38
0
        /// <summary>
        /// 以 POST 形式请求数据
        /// </summary>
        /// <param name="RequestPara"></param>
        /// <param name="Url"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string PostData(string RequestPara, string Url)
        {
            WebRequest hr = HttpWebRequest.Create(Url);

            byte[] buf         = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
            string contentType = "application/x-www-form-urlencoded";

            hr.ContentType   = contentType;
            hr.ContentLength = buf.Length;
            hr.Method        = "POST";

            System.IO.Stream RequestStream = hr.GetRequestStream();
            RequestStream.Write(buf, 0, buf.Length);
            RequestStream.Close();

            System.Net.WebResponse response = hr.GetResponse();
            StreamReader           reader   = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string ReturnVal = reader.ReadToEnd();

            reader.Close();
            response.Close();

            return(ReturnVal);
        }
Ejemplo n.º 39
0
        /// 发送请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">参数格式 “name=王武&pass=123456”</param>
        /// <returns></returns>
        public static string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";

            try
            {
                System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
                httpRquest.Method = "POST";
                //这行代码很关键,不设置ContentType将导致后台参数获取不到值
                httpRquest.ContentType = "application/json;charset=UTF-8";
                byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                //httpRquest.ContentLength = dataArray.Length;
                System.IO.Stream requestStream = null;
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    requestStream = httpRquest.GetRequestStream();
                    requestStream.Write(dataArray, 0, dataArray.Length);
                    requestStream.Close();
                }
                System.Net.WebResponse response       = httpRquest.GetResponse();
                System.IO.Stream       responseStream = response.GetResponseStream();
                System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return(backMsg);
        }
Ejemplo n.º 40
0
        /// <summary>
        /// 接收从微信支付后台发送过来的数据未验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public static WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = HttpContext.Current.Request.InputStream;
            int count          = 0;

            byte[]        buffer  = new byte[1024];
            StringBuilder builder = new StringBuilder();

            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            //转换数据格式暂不验证签名
            WxPayData data = new WxPayData();

            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                HttpContext.Current.Response.Write(res.ToXml());
                HttpContext.Current.Response.End();
            }

            return(data);
        }
Ejemplo n.º 41
0
        public static bool GetCaptive()
        {
            bool Captive = false;

            try
            {
                WebRequest request = WebRequest.Create("http://bit.bitfi.com");
                request.Method      = "GET";
                request.Timeout     = 3000;
                request.ContentType = "application/text";
                using (WebResponse response = request.GetResponse())
                    using (System.IO.Stream stream = response.GetResponseStream())
                    {
                        Captive = true;
                        stream.Close();
                        response.Close();
                    }
            }
            catch (Exception)
            {
                Captive = false;
            }
            return(Captive);
        }
Ejemplo n.º 42
0
        /// <summary>
        ///   Close the stream.
        /// </summary>
        public override void Close()
        {
            TraceOutput("Close {0:X8}", this.GetHashCode());

            // In the degenerate case, no bytes have been written to the
            // stream at all.  Need to check here, and NOT emit the
            // final block if Write has not been called.
            if (_pendingCount > 0)
            {
                WriteTransformFinalBlock();
                _s.Write(_PendingWriteBlock, 0, _pendingCount);
                _totalBytesXferred += _pendingCount;
                _pendingCount       = 0;
            }
            _s.Close();

#if WANT_TRACE
            untransformed.Close();
            transformed.Close();
            Console.WriteLine("\nuntransformed bytestream is in  {0}", traceFileUntransformed);
            Console.WriteLine("\ntransformed bytestream is in  {0}", traceFileTransformed);
#endif
            TraceOutput("-------------------------------------------------------");
        }
Ejemplo n.º 43
0
        public Bitmap GetBitmapByUrl(string url)

        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.ServicePoint.Expect100Continue = false;
            req.Method      = "GET";
            req.KeepAlive   = true;
            req.ContentType = "image/*";
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

            System.IO.Stream stream = null;
            try
            {
                stream = rsp.GetResponseStream();
                Bitmap bitmap = BitmapFactory.DecodeStream(stream);
                return(bitmap);
            }
            catch (Exception e)
            {
                LogManager.WriteSystemLog("DownLoadImage" + e.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }

                if (rsp != null)
                {
                    rsp.Close();
                }
            }
            return(null);
        }
Ejemplo n.º 44
0
        public static Result Connect(string server, string username, string password)
        {
            Result result = new Result();

            try
            {
                string ftpFileName = string.Format("ftp://{0}/{1}", server, "/results/test.txt");
                System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpFileName));
                ftpWebRequest.Credentials = new System.Net.NetworkCredential(username, password);
                ftpWebRequest.KeepAlive   = false;
                ftpWebRequest.Timeout     = 20000;
                ftpWebRequest.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpWebRequest.UseBinary   = true;
                System.IO.Stream stream = ftpWebRequest.GetRequestStream();
                stream.Close();
            }
            catch (Exception e)
            {
                result.Error.Code        = ErrorCode.CONNECT_FTP_FAIL;
                result.Error.Description = e.Message;
            }

            return(result);
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 接收从微信支付后台发送过来的数据并验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = Request.InputStream;
            int count          = 0;

            byte[]        buffer  = new byte[1024];
            StringBuilder builder = new StringBuilder();

            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());
            //转换数据格式并验证签名
            WxPayData data = new WxPayData();

            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                return(res);
            }

            return(data);
        }
Ejemplo n.º 46
0
        public void DownloadFile(string URL, string filename, System.Windows.Forms.Label label1)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[10240];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    osize = st.Read(by, 0, (int)by.Length);

                    percent     = (float)totalDownloadedByte / (float)totalBytes * 100;
                    percent     = (float)Math.Round(percent, 3);
                    label1.Text = "当前下载进度:" + percent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                MessageBox.Show("下载失败,可能是网络问题");
            }
        }
Ejemplo n.º 47
0
        private void Load(LoadMessage msg)
        {
            // Create an instance of the open file dialog box.
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter      = "Xml files (*.xml)|*.xml|Text files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;

            openFileDialog1.Multiselect = true;

            // Call the ShowDialog method to show the dialog box.
            bool?userClickedOK = openFileDialog1.ShowDialog();

            try
            {
                // Process input if the user clicked OK.
                if (userClickedOK == true)
                {
                    // Open the selected file to read.
                    System.IO.Stream fileStream = openFileDialog1.OpenFile();

                    XmlSerializer xs = new XmlSerializer(typeof(GameData));
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
                    {
                        ApplicationModel.GameModel.ImportData((GameData)xs.Deserialize(reader));
                        ApplicationViewModel.GameViewModel.ApplyModel(ApplicationModel.GameModel);
                    }
                    fileStream.Close();
                }
            }
            catch (Exception e)
            {
            }
            Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.ContextIdle, null);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Executes a command
        /// </summary>
        /// <param name="commandToExecute">The command you wish to execute</param>
        /// <returns>A response from the browser</returns>
        public Response Execute(Command commandToExecute)
        {
            if (commandToExecute == null)
            {
                throw new ArgumentNullException("commandToExecute", "commandToExecute cannot be null");
            }

            CommandInfo    info    = CommandInfoRepository.Instance.GetCommandInfo(commandToExecute.Name);
            HttpWebRequest request = info.CreateWebRequest(this.remoteServerUri, commandToExecute);

            request.Timeout = (int)this.serverResponseTimeout.TotalMilliseconds;
            request.Accept  = RequestAcceptHeader;
            if (request.Method == CommandInfo.PostCommand)
            {
                string payload = commandToExecute.ParametersAsJsonString;
                byte[] data    = Encoding.UTF8.GetBytes(payload);
                request.ContentType = ContentTypeHeader;
                System.IO.Stream requestStream = request.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
            }

            return(CreateResponse(request));
        }
Ejemplo n.º 49
0
        public virtual void RequestToJson(HttpListenerContext context, object content, string contentType)
        {
            try
            {
                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                byte[] buffer = null;

                if (content is string)
                {
                    buffer = Encoding.UTF8.GetBytes((string)content);
                }
                else if (content is List <string> || content is Playlist)
                {
                    buffer = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(content));
                }
                else
                {
                    buffer = (byte[])content;
                }

                response.Headers.Add("content-type", contentType);

                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
            }
            catch (HttpListenerException ex)
            {
                ErrorLogger.LogError(ex);
            }
        }
Ejemplo n.º 50
0
        private static string SendEventVoteRequest(string URI, string Parameters)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            req.ContentType = "json";
            req.Method      = "POST";
            LCPostModel detailReq = new LCPostModel();

            detailReq.Email       = "*****@*****.**";
            detailReq.AccessToken = "fakedtoken";
            detailReq.ContentData = JsonConvert.SerializeObject(eventModelDetail);
            Parameters            = JsonConvert.SerializeObject(detailReq);
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();
            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null)
            {
                return(null);
            }
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            return(sr.ReadToEnd().Trim());
        }
Ejemplo n.º 51
0
        private static string SendJoinRequest(string URI, string Parameters)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            //req.Proxy = new System.Net.WebProxy(ProxyString, true);
            //Add these, as we're doing a POST
            req.ContentType = "json";
            req.Method      = "POST";
            LCPostModel postModel = new LCPostModel();

            postModel.ContentData = JsonConvert.SerializeObject(userModelJoin);
            Parameters            = JsonConvert.SerializeObject(postModel);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();
            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null)
            {
                return(null);
            }
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            return(sr.ReadToEnd().Trim());
        }
Ejemplo n.º 52
0
        static void ZapiszPlik(System.IO.Stream instream, string filePath)
        {
            const int bufferLength = 8192;
            int       bytecount    = 0;
            int       counter      = 0;

            byte[] buffer = new byte[bufferLength];
            Console.WriteLine("--->Zapisuje plik {0}", filePath);
            FileStream outstream = File.Open(filePath, FileMode.Create, FileAccess.Write);

            while ((counter = instream.Read(buffer, 0, bufferLength)) > 0)
            {
                outstream.Write(buffer, 0, counter);
                Console.Write(".{0}", counter);
                bytecount += counter;
            }
            Console.WriteLine();
            Console.WriteLine("Zapisano {0} bajtów", bytecount);

            outstream.Close();
            instream.Close();
            Console.WriteLine();
            Console.WriteLine("-->Plik {0} zapisany", filePath);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// c#,.net 下载文件
 /// </summary>
 /// http://localhost:8080/tomcat.zip
 /// <param name="URL">下载文件地址</param>
 ///
 /// <param name="Filename">下载后的存放地址</param>
 /// <param name="Prog">用于显示的进度条</param>
 ///
 public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog)
 {
     try
     {
         System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
         System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
         long totalBytes = myrp.ContentLength;
         if (prog != null)
         {
             prog.Maximum = (int)totalBytes;
         }
         System.IO.Stream st = myrp.GetResponseStream();
         System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
         long             totalDownloadedByte = 0;
         byte[]           by = new byte[1024];
         int osize           = st.Read(by, 0, (int)by.Length);
         while (osize > 0)
         {
             totalDownloadedByte = osize + totalDownloadedByte;
             System.Windows.Forms.Application.DoEvents();
             so.Write(by, 0, osize);
             if (prog != null)
             {
                 prog.Value = (int)totalDownloadedByte;
             }
             osize = st.Read(by, 0, (int)by.Length);
         }
         so.Close();
         st.Close();
     }
     catch (System.Exception)
     {
         MessageBox.Show("硬盘读写或者网络连接异常!!\n请检查你相关功能是否能正常使用!请稍后重试^_^~", "更新失败:");
         Application.Exit();
     }
 }
Ejemplo n.º 54
0
        /// <summary>
        /// 带进度的下载文件
        /// </summary>
        /// <param name="URL">下载文件地址</param>
        /// <param name="Filename">下载后的存放地址</param>
        ///
        public bool DownloadFileProg(string URL, string filename)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                this.prog_totalBytes = (int)totalBytes;
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[1024];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    this.prog_Value = (int)totalDownloadedByte;
                    osize           = st.Read(by, 0, (int)by.Length);

                    percent        = (float)totalDownloadedByte / (float)totalBytes * 100;
                    this.la_status = "当前下载进度" + percent.ToString() + "%";
                }
                so.Close();
                st.Close();
                return(true);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
 /// <summary>
 /// 图片url链接转化为字节
 /// </summary>
 /// <param name="url"></param>
 /// <returns></returns>
 public static byte[] GetURLImageBytes(string url)
 {
     byte[] img = null;
     try
     {
         System.Net.WebRequest  webreq = System.Net.WebRequest.Create(url);
         System.Net.WebResponse webres = webreq.GetResponse();
         using (System.IO.Stream stream = webres.GetResponseStream())
         {
             using (System.IO.MemoryStream mStream = new MemoryStream())
             {
                 stream.CopyTo(mStream);
                 img = mStream.GetBuffer();
                 stream.Close();
                 mStream.Close();
             }
         }
     }
     catch (Exception ex)
     {
         //LogHelper.WriteErrorLog(typeof(ImageHelper), ex);
     }
     return(img);
 }
Ejemplo n.º 56
0
        public void Close()
        {
            try
            {
                if (IsOpened)
                {
                    if (!_isSsl)
                    {
                        //NOTE: returns !fatal => can not use standard ExecuteNonQuery call (should not throw exception)
                        var responseSentences = CallCommandSync(new string[] { "/quit" });
                        //TODO should return single response of ApiFatalSentence with message "session terminated on request" - test and warning if not?
                    }
                    else
                    {
                        //NOTE: No result returned when SSL & /quit => do not read response (possible bug in SSL-API?)
                        WriteCommand(new string[] { "/quit" });
                    }
                }
            }
            catch (IOException)
            {
                // catch exception if connection is closed
            }

            //if (_tcpConnection.Connected)
            //{
#if NET20 || NET35 || NET40 || NET45 || NET451 || NET452
            _tcpConnectionStream.Close();
            _tcpConnection.Close();
#else
            _tcpConnectionStream.Dispose();
            _tcpConnection.Dispose();
#endif
            //}
            _isOpened = false;
        }
Ejemplo n.º 57
0
        private void ButtonGo_Click(object sender, System.EventArgs e)
        {
            string Address = targetURI.Text;

            if (Address != "")
            {
                //create an instance of the WebClient.
                System.Net.WebClient MyClient = new System.Net.WebClient();
                //create a stream object to get the stream from the OpenRead method.
                System.IO.Stream MyStream = MyClient.OpenRead(Address);
                //create a streamreader to parse through the stream.
                System.IO.StreamReader MyStreamReader = new System.IO.StreamReader(MyStream);

                string NewLine;

                //loop through the stream and put the output in the textbox.
                while ((NewLine = MyStreamReader.ReadLine()) != null)
                {
                    textOutput.AppendText(NewLine + "\r\n");
                }

                MyStream.Close();
            }
        }
Ejemplo n.º 58
0
        private void post2Url(string postUrl, string content, Encoding dataEncode)
        {
            try
            {
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method      = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                byte[] byteArray = dataEncode.GetBytes(content);
                webReq.ContentLength = byteArray.Length;
                System.IO.Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();

                StreamReader sr  = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string       ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Cleans up the resources associated with this AiffFileReader
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         // Release managed resources.
         if (waveStream != null)
         {
             // only dispose our source if we created it
             if (ownInput)
             {
                 waveStream.Close();
             }
             waveStream = null;
         }
     }
     else
     {
         System.Diagnostics.Debug.Assert(false, "AiffFileReader was not disposed");
     }
     // Release unmanaged resources.
     // Set large fields to null.
     // Call Dispose on your base class.
     base.Dispose(disposing);
 }
Ejemplo n.º 60
0
        //附件下载
        public ActionResult fj_xz(string code)
        {
            DataTable table = DataHelper.GetDataTable("select * from bill_fjb where list_id = '" + code + "'");

            if (table.Rows.Count == 0)
            {
                return(Content("<script>alert('没有附件!');</script>"));
            }
            string a = table.Rows[0]["djUrl"].ToString();

            //byte[] File = System.Text.Encoding.Default.GetBytes(a);
            //byte[] File = (byte[])a;
            byte[] File     = Encoding.UTF8.GetBytes(a);
            string filename = table.Rows[0]["djName"].ToString();

            Response.ContentType = "Application/plain";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            this.Response.Clear();
            System.IO.Stream fs = this.Response.OutputStream;
            fs.Write(File, 0, File.Length);
            fs.Close();
            this.Response.End();
            return(Json(new { success = "ok" }, JsonRequestBehavior.AllowGet));
        }