private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response, ref Stream responseStream, ref StreamReader reader) { if (request != null) { request = null; } if (response != null) { response.Close(); response = null; } if (responseStream != null) { responseStream.Close(); responseStream.Dispose(); responseStream = null; } if (reader != null) { reader.Close(); reader.Dispose(); reader = null; } }
public static async Task<long> CopyStreamsAsyncParallel(Stream src, Stream dst) { long numCopied = 0; byte[][] buffer = new byte[2][]; buffer[0] = new byte[0x1000]; buffer[1] = new byte[0x1000]; var index = 0; int numRead = await src.ReadAsync(buffer[index], 0, buffer[index].Length); while (numRead > 0) { var writeAsync = dst.WriteAsync(buffer[index], 0, numRead); index = index ^= 1; var readAsync = src.ReadAsync(buffer[index], 0, buffer[index].Length); Task.WaitAll(writeAsync, readAsync); numRead = readAsync.Result; numCopied += numRead; } await dst.FlushAsync(); src.Dispose(); dst.Dispose(); return numCopied; }
/// <exception cref="InvalidImageException"> /// ストリームから読みだされる画像データが不正な場合にスローされる /// </exception> protected MemoryImage(Stream stream) { try { this.Image = Image.FromStream(stream); } catch (ArgumentException e) { stream.Dispose(); throw new InvalidImageException("Invalid image", e); } catch (OutOfMemoryException e) { // GDI+ がサポートしない画像形式で OutOfMemoryException がスローされる場合があるらしい stream.Dispose(); throw new InvalidImageException("Invalid image?", e); } catch (ExternalException e) { // 「GDI+ で汎用エラーが発生しました」という大雑把な例外がスローされる場合があるらしい stream.Dispose(); throw new InvalidImageException("Invalid image?", e); } catch (Exception) { stream.Dispose(); throw; } this.Stream = stream; }
public void saveOptions(Options options) { XmlSerializer formatter = new XmlSerializer(typeof(Options)); try { stream = File.Open(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "options.xml", FileMode.OpenOrCreate); formatter.Serialize(stream, options); stream.Dispose(); } catch { stream.Dispose(); } }
/// <summary> /// The read sequence from stream. /// </summary> /// <param name="stream"> /// The stream. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string ReadSequenceFromStream(Stream stream) { var input = new byte[stream.Length]; stream.Read(input, 0, (int)stream.Length); stream.Dispose(); return Encoding.UTF8.GetString(input); }
public GenericBinaryFile(Stream stream) { _path = string.Empty; _data = new byte[stream.Length]; stream.Read(_data, 0, (int)stream.Length); stream.Dispose(); }
internal void start(TcpListener listen, int count) { try { File.AppendAllText(@".\\socketLog.txt", DateTime.Now.ToString("HH:mm:ss") + " | Listener: Waiting for a connection" + Environment.NewLine); client = listen.AcceptTcpClient(); File.AppendAllText(@".\\socketLog.txt", DateTime.Now.ToString("HH:mm:ss") + " | Listener: Got a connection" + Environment.NewLine); s = client.GetStream(); sr = new StreamReader(s); sw = new StreamWriter(s); sw.AutoFlush = true; string res = slaveStates.process(sr.ReadLine()); sw.WriteLine(res); socketAcceptClass.connections++; sr.Close(); sr.Dispose(); s.Close(); s.Dispose(); client.Close(); } catch (Exception e) { File.AppendAllText(@".\\socketLog.txt", DateTime.Now.ToString("HH:mm:ss") + " | Listener Exception: " + e.ToString() + Environment.NewLine); } }
/// <summary> /// Closes the given file and releases all resources associated with it. /// </summary> public override void Close(Stream file) { if (file != null) { file.Dispose(); } }
public Boolean WriteBinaryMap(String FileName) { try { serialzed_stream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write); binary_formatter = new BinaryFormatter(); xmap = new FileFormat(); WriteMapData(); } catch (Exception e) { #if(DEBUG) MessageBox.Show(e.Message, "Save Map Error", MessageBoxButtons.OK, MessageBoxIcon.Error); #else // RELEASE MessageBox.Show("Error while saving map, the file could be in use by another program, or is write protected", "Save Map Error", MessageBoxButtons.OK, MessageBoxIcon.Error); #endif return false; } finally { serialzed_stream.Close(); serialzed_stream.Dispose(); } // Write to file Ok return true; }
/// <summary> /// запуск синхронизации сущности на филиале /// </summary> /// <param name="aInValues">Поток с входными данными. Это строка = сериализованный класс Upsmile.Sync.BasicClasses.USInServiceValues</param> /// <returns>Строка. В случае успешной синхронизации строка пустая. В противном случае выводится ошибка</returns> public string EntitySync(Stream aInValues) { USInServiceRetValues lResult = new USInServiceRetValues() { Result = 1, ErrorMessage = string.Empty }; // входные параметры элемент класса USInServiceValues // сериализованные JSON try { // получение потока и занесение его в строку string lJsonInValues = StreamToStr(aInValues); this.WriteLog(USLogLevel.Trace, "EntitySync: поток занесен в строку"); aInValues.Dispose(); // десериализация входных данных var lInValues = Newtonsoft.Json.JsonConvert.DeserializeObject<USInServiceValues>(lJsonInValues); lJsonInValues = string.Empty; this.WriteLog(USLogLevel.Trace, "EntitySync: EntityTypeId = {0} входные данные десериализованы", lInValues.EntityTypeId); // запуск синхронизации var ldicSync = new USExDicSync(); var lSyncErrorMessage = string.Empty; var lSyncResult = ldicSync.DicSync(lInValues.EntityTypeId, lInValues.JsonEntityData, ref lSyncErrorMessage); lResult.Result = lSyncResult; lResult.ErrorMessage = lSyncErrorMessage; lInValues = null; } catch (Exception e) { this.WriteLogException(e.ToString(), e); lResult.Result = 0; lResult.ErrorMessage = Newtonsoft.Json.JsonConvert.SerializeObject(e); } return Newtonsoft.Json.JsonConvert.SerializeObject(lResult); }
/// <summary> /// Compresses the response stream if the browser allows it. /// </summary> private static MemoryStream CompressResponse(Stream responseStream, HttpApplication app, string key) { MemoryStream dataStream = new MemoryStream(); StreamCopy(responseStream, dataStream); responseStream.Dispose(); byte[] buffer = dataStream.ToArray(); dataStream.Dispose(); MemoryStream ms = new MemoryStream(); Stream compress = null; if (IsEncodingAccepted(DEFLATE)) { compress = new DeflateStream(ms, CompressionMode.Compress); app.Application.Add(key + "enc", DEFLATE); } else if (IsEncodingAccepted(GZIP)) { compress = new GZipStream(ms, CompressionMode.Compress); app.Application.Add(key + "enc", DEFLATE); } compress.Write(buffer, 0, buffer.Length); compress.Dispose(); return ms; }
/// <summary> /// 返回文件真实后缀 /// </summary> /// <param name="stream"></param> /// <param name="closeStream"></param> /// <returns></returns> public static FileExt GetFileExt(Stream stream, bool closeStream = false) { System.IO.BinaryReader br = new System.IO.BinaryReader(stream); StringBuilder sb = new StringBuilder(); byte buffer; try { buffer = br.ReadByte(); sb.Append(buffer.ToString()); buffer = br.ReadByte(); sb.Append(buffer.ToString()); return (FileExt)Convert.ToInt32(sb.ToString()); } catch { return FileExt.None; } finally { if (closeStream) { stream.Close(); stream.Dispose(); } else { stream.Position = 0; } } }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</param> /// <param name="messageStream">The message stream to write the payload to.</param> /// <param name="encoding">The encoding to use for the payload.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="synchronous">true if the output should be written synchronously; false if it should be written asynchronously.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> private ODataMetadataOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { Debug.Assert(synchronous, "Metadata output context is only supported in synchronous operations."); try { this.messageOutputStream = messageStream; this.xmlWriter = ODataAtomWriterUtils.CreateXmlWriter(messageStream, messageWriterSettings, encoding); } catch (Exception e) { // Dispose the message stream if we failed to create the output context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
public Texture (Stream stream, TextureSettings settings = null, bool leaveOpen = true) { byte[] data = PngLoader.Decode(stream, out _size, out _format); this.Initialize(data, settings); if (!leaveOpen) stream.Dispose(); }
public void ReplaceAtomically(Stream newData, Stream newLog) { var newDataStream = ((FileStream)newData); string dataTempName = newDataStream.Name; newDataStream.Flush(); newDataStream.Dispose(); var newLogStream = ((FileStream)newLog); string logTempName = newLogStream.Name; newLogStream.Flush(); newLogStream.Dispose(); newData.Dispose(); newLog.Dispose(); log.Dispose(); data.Dispose(); string renamedDataFile = dataPath + ".rename_op"; string renamedLogFile = logPath + ".rename_op"; File.Move(dataPath, renamedDataFile); File.Move(logPath, renamedLogFile); File.Move(logTempName, logPath); File.Move(dataTempName, dataPath); File.Delete(renamedDataFile); File.Delete(renamedLogFile); this.data = File.Open(dataPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); this.log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); }
public Art(Stream input) { ImageData=new byte[input.Length]; input.Read(ImageData, 0, ImageData.Length); input.Close(); input.Dispose(); }
public void ReplaceAtomically(Stream newData, Stream newLog) { var newDataStream = ((FileStream)newData); string dataTempName = newDataStream.Name; newDataStream.Flush(); newDataStream.Dispose(); var newLogStream = ((FileStream)newLog); string logTempName = newLogStream.Name; newLogStream.Flush(); newLogStream.Dispose(); newData.Dispose(); newLog.Dispose(); log.Dispose(); data.Dispose(); string renamedDataFile = dataPath + ".rename_op"; string renamedLogFile = logPath + ".rename_op"; File.Move(dataPath, renamedDataFile); File.Move(logPath, renamedLogFile); File.Move(logTempName, logPath); File.Move(dataTempName, dataPath); File.Delete(renamedDataFile); File.Delete(renamedLogFile); OpenFiles(); }
/// <summary> /// Reads a SERI from a XML file. /// </summary> /// <param name="xmlData">The Stream of the XML file</param> /// <returns></returns> public static SERI getSERI(Stream xmlData) { XmlSerializer deserializer = new XmlSerializer(typeof(SERI)); SERI output = (SERI)deserializer.Deserialize(xmlData); xmlData.Dispose(); return output; }
internal ODataRawInputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind) : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "stream != null"); Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported"); ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); try { this.stream = messageStream; this.encoding = encoding; this.readerPayloadKind = readerPayloadKind; } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
private WaveFileReader(Stream inputStream, bool ownInput) { this.waveStream = inputStream; var chunkReader = new WaveFileChunkReader(); try { chunkReader.ReadWaveHeader(inputStream); this.waveFormat = chunkReader.WaveFormat; this.dataPosition = chunkReader.DataChunkPosition; this.dataChunkLength = chunkReader.DataChunkLength; this.chunks = chunkReader.RiffChunks; } catch { if (ownInput) { inputStream.Dispose(); } throw; } Position = 0; this.ownInput = ownInput; }
private ODataJsonOutputContext(ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { try { Stream asynchronousOutputStream; this.messageOutputStream = messageStream; if (synchronous) { asynchronousOutputStream = messageStream; } else { this.asynchronousOutputStream = new AsyncBufferedStream(messageStream); asynchronousOutputStream = this.asynchronousOutputStream; } this.textWriter = new StreamWriter(asynchronousOutputStream, encoding); this.jsonWriter = new Microsoft.Data.OData.Json.JsonWriter(this.textWriter, messageWriterSettings.Indent); } catch (Exception exception) { if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null)) { messageStream.Dispose(); } throw; } }
async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context) { try { var buffer = new byte[_chunkSize]; using (var inputStream = OpenInputStream()) { var length = (int)inputStream.Length; var bytesRead = 1; while (length > 0 && bytesRead > 0) { bytesRead = inputStream.Read(buffer, 0, Math.Min(length, buffer.Length)); await outputStream.WriteAsync(buffer, 0, bytesRead); length -= bytesRead; } } } catch (HttpException) { } finally { outputStream.Close(); outputStream.Dispose(); } }
public PaletteTable(Stream stream, bool leaveOpen = true) { ReadPaletteEntries(stream); if(!leaveOpen) stream.Dispose(); }
private ODataAtomOutputContext(ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { try { Stream asynchronousOutputStream; this.messageOutputStream = messageStream; if (synchronous) { asynchronousOutputStream = messageStream; } else { this.asynchronousOutputStream = new AsyncBufferedStream(messageStream); asynchronousOutputStream = this.asynchronousOutputStream; } this.xmlRootWriter = ODataAtomWriterUtils.CreateXmlWriter(asynchronousOutputStream, messageWriterSettings, encoding); this.xmlWriter = this.xmlRootWriter; } catch (Exception exception) { if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null)) { messageStream.Dispose(); } throw; } }
public EPubFile(Stream s) { try { zip = new ZipFile(s); string mpath = getRootFromContainer (GetContent("META-INF/container.xml")); OPFParser.ParseStream(GetContent(mpath), mpath, out Manifest, out Spine); if (Spine.TocId == null) { Toc = new TableOfContents(); } else { string tocPath = Manifest.GetById(Spine.TocId).Linkref; Toc = NCXParser.ParseStream(GetContent(tocPath), tocPath); } stream = s; } catch (Exception ex) { s.Dispose(); throw ex; } }
public static Stream GetStream(Stream fileStream) { Stream objFileStream = null; try { GZipStream gzip = new GZipStream(fileStream, CompressionMode.Decompress); MemoryStream memStream = new MemoryStream(); byte[] bytes = new byte[1024]; int bytesRead = -1; while (bytesRead != 0) { bytesRead = gzip.Read(bytes, 0, 1024); memStream.Write(bytes, 0, bytesRead); memStream.Flush(); } memStream.Position = 0; objFileStream = memStream; gzip.Close(); gzip.Dispose(); fileStream.Dispose(); } catch (Exception) { fileStream.Position = 0; objFileStream = fileStream; } return objFileStream; }
static void Main(string[] args) { _readBuffer = new byte[960]; Console.WriteLine("Opening \"{0}\" for playback", OpenALHelper.PlaybackDevices[0].DeviceName); Console.WriteLine("Opening \"{0}\" for capture", OpenALHelper.CaptureDevices[0].DeviceName); _playback = OpenALHelper.PlaybackDevices[0].OpenStream(48000, OpenALAudioFormat.Mono16Bit); _playback.Listener.Position = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f }; _playback.Listener.Velocity = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f }; _playback.Listener.Orientation = new Orientation() { At = new Vector3() { X = 0.0f, Y = 0.0f, Z = 1.0f }, Up = new Vector3() { X = 0.0f, Y = 1.0f, Z = 0.0f } }; _playback.ALPosition = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f }; _playback.Velocity = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f }; _capture = OpenALHelper.CaptureDevices[0].OpenStream(48000, OpenALAudioFormat.Mono16Bit, 10); _capture.BeginRead(_readBuffer, 0, _readBuffer.Length, Callback, null); while (true) { PrintUI(); if (ProcessInput()) break; } _playback.Close(); _playback.Dispose(); _capture.Close(); _capture.Dispose(); }
public static SessionSecurityTokenHandler RSASessionTokenHandler(Stream certificateStream, string certificatePassphrase, System.IdentityModel.Services.Configuration.FederationConfigurationCreatedEventArgs e) { X509Certificate2 certificate; //get the certificate as an app resource using (var memoryStream = new MemoryStream()) { //create an x509 cert object certificateStream.CopyTo(memoryStream); certificate = new X509Certificate2(memoryStream.ToArray(), certificatePassphrase, X509KeyStorageFlags.Exportable|X509KeyStorageFlags.MachineKeySet); certificateStream.Dispose(); } //create a set of cookie transforms to sign and encrypt the session token with - using the certificate var sessionTransforms = new List<CookieTransform>(new CookieTransform[] { new DeflateCookieTransform(), new RsaEncryptionCookieTransform(certificate), new RsaSignatureCookieTransform(certificate) }); e.FederationConfiguration.ServiceCertificate = certificate; //create a new session security token handler using the collection of cookie transforms return new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly()); }
/// <summary> /// Initializes a new instance of <see cref="DynamicYaml"/> from the specified stream. /// </summary> /// <param name="stream">A stream that contains a YAML content. The stream will be disposed</param> /// <param name="disposeStream">Dispose the stream when reading the YAML content is done. <c>true</c> by default</param> public DynamicYaml(Stream stream, bool disposeStream = true) { if (stream == null) throw new ArgumentNullException(nameof(stream)); // transform the stream into string. string assetAsString; try { using (var assetStreamReader = new StreamReader(stream, Encoding.UTF8)) { assetAsString = assetStreamReader.ReadToEnd(); } } finally { if (disposeStream) { stream.Dispose(); } } // Load the asset as a YamlNode object var input = new StringReader(assetAsString); yamlStream = new YamlStream(); yamlStream.Load(input); if (yamlStream.Documents.Count != 1 || !(yamlStream.Documents[0].RootNode is YamlMappingNode)) throw new YamlException("Unable to load the given stream"); }
protected void BeginLoadBitmapImpl(Stream stream, TileIndex id) { Dispatcher.BeginInvoke((Action)(() => { BitmapImage bmp = new BitmapImage(); SubscribeBitmapEvents(bmp); pendingBitmaps.Add(bmp, id); MemoryStream memStream = new MemoryStream(); stream.CopyTo(memStream); memStream.Seek(0, SeekOrigin.Begin); stream.Dispose(); bmp.BeginInit(); bmp.StreamSource = memStream; bmp.CacheOption = BitmapCacheOption.OnLoad; bmp.EndInit(); if (!bmp.IsDownloading) { UnsubscribeBitmapEvents(bmp); ReportSuccess(memStream, bmp, id); pendingBitmaps.Remove(bmp); bmp.Freeze(); } })); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _handshaker?.Dispose(); _stream?.Dispose(); } }
private void LoadPicture(int i) { String url; try { url = json["hits"][i]["thumbnail_url"]; } catch { url = ""; Bitmap DefaultImage = Properties.Resources.NotFound; ImageList.Images.Add(DefaultImage); GatherProductInfo(i); return; } if (url == "") { Bitmap DefaultImage = Properties.Resources.NotFound; ImageList.Images.Add(DefaultImage); GatherProductInfo(i); return; } //load image from url System.Net.WebRequest request = System.Net.WebRequest.Create(url); try { System.Net.WebResponse resp = request.GetResponse(); System.IO.Stream respStream = resp.GetResponseStream(); Bitmap bmp = new Bitmap(respStream); respStream.Dispose(); ImageList.Images.Add(bmp); GatherProductInfo(i); } //catch bad url catch { Bitmap DefaultImage = Properties.Resources.NotFound; ImageList.Images.Add(DefaultImage); GatherProductInfo(i); return; } }
/// <summary> /// Writes a stream to another stream asynchronously /// </summary> /// <param name="readStream">the stream you need to read.</param> /// <param name="writeStream">the stream you want to write to.</param> /// <param name="onPercentageUpdate">Action to take on write percentage update.</param> public static async Task ReadWriteStreamAsync(Stream readStream, Stream writeStream, Action <int> onPercentageUpdate) { onPercentageUpdate?.Invoke(0); int Length = 65536; byte[] buffer = new byte[Length]; long totalBytes = readStream.Length; long receivedBytes = 0; int i = 0; int updateFrequency = 2; for (;;) { int bytesRead; if (i % updateFrequency == 0) { bytesRead = await readStream.ReadAsync(buffer, 0, buffer.Length); } else { bytesRead = readStream.Read(buffer, 0, buffer.Length); } if (bytesRead == 0) { await Task.Yield(); break; } writeStream.Write(buffer, 0, bytesRead); receivedBytes += bytesRead; if (i++ % updateFrequency == 0) { onPercentageUpdate?.Invoke((int)(((float)receivedBytes / totalBytes) * 100)); } } onPercentageUpdate?.Invoke(100); readStream.Dispose(); writeStream.Dispose(); }
/// <summary> /// Generate a list of DatItem objects from the header values in an archive /// </summary> /// <param name="omitFromScan">Hash representing the hashes that should be skipped</param> /// <param name="date">True if entry dates should be included, false otherwise (default)</param> /// <returns>List of DatItem objects representing the found data</returns> /// <remarks>TODO: All instances of Hash.DeepHashes should be made into 0x0 eventually</remarks> public override List <BaseFile> GetChildren(Hash omitFromScan = Hash.DeepHashes, bool date = false) { List <BaseFile> found = new List <BaseFile>(); string gamename = Path.GetFileNameWithoutExtension(_filename); try { SharpCompress.Archives.SevenZip.SevenZipArchive sza = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(Utilities.TryOpenRead(_filename)); foreach (SevenZipArchiveEntry entry in sza.Entries.Where(e => e != null && !e.IsDirectory)) { // If secure hashes are disabled, do a quickscan if (omitFromScan == Hash.SecureHashes) { found.Add(new BaseFile { Filename = entry.Key, Size = entry.Size, CRC = BitConverter.GetBytes(entry.Crc), Date = (date && entry.LastModifiedTime != null ? entry.LastModifiedTime?.ToString("yyyy/MM/dd hh:mm:ss") : null), Parent = gamename, }); } // Otherwise, use the stream directly else { Stream entryStream = entry.OpenEntryStream(); BaseFile sevenZipEntryRom = Utilities.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan); sevenZipEntryRom.Filename = entry.Key; sevenZipEntryRom.Parent = gamename; sevenZipEntryRom.Date = (date && entry.LastModifiedTime != null ? entry.LastModifiedTime?.ToString("yyyy/MM/dd hh:mm:ss") : null); found.Add(sevenZipEntryRom); entryStream.Dispose(); } } // Dispose of the archive sza.Dispose(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return(null); } return(found); }
/// <summary> /// Gets an embedded text file. /// </summary> /// <param name="file"></param> /// <returns></returns> public static String GetEmbeddedTextFile(string file) { String ret = null; try { if (pp == null) { pp = new PlayerParser(""); } System.IO.Stream s = null; StreamReader reader = null; try { string[] embeddedFiles = pp.GetType().Assembly.GetManifestResourceNames(); for (int i = 0; i < embeddedFiles.Length; i++) { if (embeddedFiles[i].EndsWith(file, StringComparison.InvariantCultureIgnoreCase)) { s = pp.GetType().Assembly.GetManifestResourceStream(embeddedFiles[i]); break; } } if (s != null) { reader = new StreamReader(s); ret = reader.ReadToEnd(); } } finally { if (reader != null) { reader.Dispose(); } if (s != null) { s.Dispose(); } } } catch (Exception) { AddError("Error getting file " + file); } return(ret); }
private string GetRequestText(HttpRequest request) { System.IO.Stream str = request.InputStream; int count = 0; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); while ((count = str.Read(buffer, 0, 1024)) > 0) { builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); } str.Flush(); str.Close(); str.Dispose(); return(builder.ToString()); }
public static Map <String, String> zippedTextFiles(String _zipFileName) { Map <String, String> map_ = new Map <String, String>(); ZipArchive zip_ = ZipFile.OpenRead(_zipFileName); ReadOnlyCollection <ZipArchiveEntry> e_ = zip_.Entries; foreach (ZipArchiveEntry e in e_) { System.IO.Stream str_ = e.Open(); using (StreamReader reader_ = new StreamReader(str_)) { map_.put(e.FullName, reader_.ReadToEnd()); } str_.Dispose(); } return(map_); }
public NegotiationResult Negotiate(System.IO.Stream stream) { DelimWriteBuffered(stream, ProtocolIdBytes); var token = ReadNextToken(stream); if (token == null) { return(null); } if (token != ProtocolId) { stream.Dispose(); throw ErrIncorrectVersion; } while (true) { token = ReadNextToken(stream); if (token == null) { break; } switch (token) { case "ls": Ls(stream); break; default: var handler = FindHandler(token); if (handler == null) { DelimWriteBuffered(stream, BytesNotAvailable); continue; } DelimWriteBuffered(stream, Encoding.UTF8.GetBytes(token)); return(new NegotiationResult(token, handler)); } } return(null); }
/// <summary> /// 提交数据并获取返回内容 /// </summary> /// <param name="Url"></param> /// <param name="Args"></param> /// <param name="enc"></param> /// <returns></returns> public string Post(string Url, string Args, Encoding enc) { string respHTML = ""; //try { System.Net.HttpWebRequest httpReq; System.Net.HttpWebResponse httpResp; System.Uri httpURL = new System.Uri(Url); httpReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL); httpReq.Method = "POST"; httpReq.Headers.Add("Cookie", _cookies.ToString()); byte[] bs = enc.GetBytes(Args); httpReq.KeepAlive = false; httpReq.ContentType = "application/x-www-form-urlencoded"; httpReq.ContentLength = bs.Length; httpReq.Timeout = 30000; //httpReq. //post数据 using (System.IO.Stream reqStream = httpReq.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse(); SetCookies("" + httpResp.Headers["Set-Cookie"]); using (System.IO.Stream MyStream = httpResp.GetResponseStream()) { System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8); respHTML = reader.ReadToEnd(); reader.Dispose(); MyStream.Dispose(); } httpResp.Close(); httpReq = null; return(respHTML); }
public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, 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; 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); percent = (float)totalDownloadedByte / (float)totalBytes * 100; label1.Text = "当前补丁下载进度" + percent.ToString() + "%"; System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 } so.Close(); st.Close(); so.Dispose(); st.Dispose(); } catch (System.Exception) { label1.Text = "下载地址出错"; throw; } }
public static Person loadPerson(Person p, string filename = "test.dat") { //Create the stream and and the file object to it System.IO.Stream fs = File.Open(filename, FileMode.Open); //The object that will format our data to binary while streaming BinaryFormatter formatter = new BinaryFormatter(); //Serialize the data Object obj = formatter.Deserialize(fs); p = (Person)obj; //cast the object as our person class before returning fs.Flush(); fs.Close(); fs.Dispose(); return(p); }
private ODataRawInputContext(ODataFormat format, System.IO.Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind) : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver) { ExceptionUtils.CheckArgumentNotNull <ODataFormat>(format, "format"); ExceptionUtils.CheckArgumentNotNull <ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings"); try { this.stream = messageStream; this.encoding = encoding; this.readerPayloadKind = readerPayloadKind; } catch (Exception exception) { if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null)) { messageStream.Dispose(); } throw; } }
private static bool Upload(string FileName, byte[] Image, string FtpUsername, string FtpPassword) { try { System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(FileName); clsRequest.Credentials = new System.Net.NetworkCredential(FtpUsername, FtpPassword); clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; System.IO.Stream clsStream = clsRequest.GetRequestStream(); clsStream.Write(Image, 0, Image.Length); clsStream.Close(); clsStream.Dispose(); return(true); } catch { return(false); } }
void Image_Change() { try { string[] a = null; string[] b = null; int suiji = intSuijishu(1, 6); Task.Run(() => { WebClient webClient = new WebClient(); a = Encoding.UTF8.GetString(webClient.DownloadData("http://106.14.64.250/api/" + suiji + ".html")).Split('#'); webClient.Dispose(); b = a[1].Split('|'); System.Net.WebRequest webreq = System.Net.WebRequest.Create("http://106.14.64.250/api/" + b[1]); System.Net.WebResponse webres = webreq.GetResponse(); System.IO.Stream stream = webres.GetResponseStream(); System.Drawing.Image img1 = System.Drawing.Image.FromStream(stream); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img1); IntPtr hBitmap = bmp.GetHbitmap(); this.Dispatcher.BeginInvoke(new Action(() => { ImageLabel1.Content = a[0]; ImageLabel.Text = b[0]; Image.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); })); stream.Dispose(); webreq.Abort(); webres.Dispose(); img1.Dispose(); bmp.Dispose(); GC.Collect(); this.Dispatcher.BeginInvoke(new Action(() => { Image_Loading.Visibility = Visibility.Collapsed; })); }); } catch { Image_Loading.Visibility = Visibility.Collapsed; } }
public static string PostInput(Stream InputStream, Encoding encoding) { try { System.IO.Stream s = InputStream; int count = 0; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(encoding.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); return(builder.ToString()); } catch (Exception ex) { throw ex; } }
public string GetPost() { try { System.IO.Stream s = HttpContext.Current.Request.InputStream; int count = 0; byte[] buffer = new byte[s.Length]; StringBuilder builder = new StringBuilder(); while ((count = s.Read(buffer, 0, buffer.Length)) > 0) { builder.Append(HttpContext.Current.Request.ContentEncoding.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); return(builder.ToString()); } catch (Exception ex) { throw ex; } }
public static Image ToImage(this string url) { var image = new Image(); try { System.Net.WebRequest webreq = System.Net.WebRequest.Create(url); System.Net.WebResponse webres = webreq.GetResponse(); System.IO.Stream stream = webres.GetResponseStream(); System.Drawing.Image img1 = System.Drawing.Image.FromStream(stream); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img1); IntPtr hBitmap = bmp.GetHbitmap(); System.Windows.Media.ImageSource WpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); image.Source = WpfBitmap; image.Stretch = Stretch.Uniform; stream.Dispose(); } catch (Exception e) { return(null); } return(image); }
//获取NotifyXML public static XmlDocument GetPayNotifyXml(HttpRequest request) { System.IO.Stream s = Current.Request.InputStream; int count = 0; byte[] buffer = new byte[1024]; System.Text.StringBuilder builder = new System.Text.StringBuilder(); while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); string xmlString = builder.ToString(); XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlString); return(xml); }
public void Close() { if (_stream == null) { return; } try { finish(); } finally { end(); if (!_leaveOpen) { _stream.Dispose(); } _stream = null; } }
public new void Dispose() { if (_stream == null) { return; } try { Finish(); } finally { End(); if (!_leaveOpen) { _stream.Dispose(); } _stream = null; } }
public static byte[] ReadToEnd(System.IO.Stream inputStream) { if (!inputStream.CanRead) { throw new ArgumentException(); } // This is optional if (inputStream.CanSeek) { inputStream.Seek(0, SeekOrigin.Begin); } byte[] output = new byte[inputStream.Length]; int bytesRead = inputStream.Read(output, 0, output.Length); inputStream.Dispose();//.Close(); //Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length"); return(output); }
/// <summary> /// Disposes this WaveStream /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (mp3Stream != null) { if (ownInputStream) { mp3Stream.Dispose(); } mp3Stream = null; } if (decompressor != null) { decompressor.Dispose(); decompressor = null; } } base.Dispose(disposing); }
private System.Drawing.Bitmap getNetImg(string imgUrl) { System.Drawing.Bitmap result; try { System.Random random = new System.Random(); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(imgUrl + "?aid=&" + random.NextDouble()); System.Net.WebResponse response = webRequest.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); System.Drawing.Image image = System.Drawing.Image.FromStream(responseStream); responseStream.Close(); responseStream.Dispose(); result = (System.Drawing.Bitmap)image; } catch (System.Exception var_5_57) { result = new System.Drawing.Bitmap(100, 100); } return(result); }
// 获取POST返回来的数据 private string PostInput() { try { System.IO.Stream s = Request.InputStream; int count = 0; byte[] buffer = new byte[1024]; System.Text.StringBuilder builder = new System.Text.StringBuilder(); while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); return(builder.ToString()); } catch (Exception ex) { throw ex; } }
public static Image DownloadImage(string _URL) { Image _tmpImage = null; try { // Open a connection System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL); _HttpWebRequest.AllowWriteStreamBuffering = true; // You can also specify additional header values like the user agent or the referer: (Optional) _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"; _HttpWebRequest.Referer = "http://www.google.com/"; // set timeout for 20 seconds (Optional) _HttpWebRequest.Timeout = 20000; // Request response: System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse(); // Open data stream: System.IO.Stream _WebStream = _WebResponse.GetResponseStream(); // convert webstream to image _tmpImage = Image.FromStream(_WebStream); // Cleanup _WebStream.Close(); _WebResponse.Close(); _WebStream.Dispose(); } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); return(null); } return(_tmpImage); }
private void bgMiddleImage_DoWork(object sender, DoWorkEventArgs e) { try { MaxId = ""; MaxId = GetMaxId(); string filename = lblPath.Text; FileInfo objFile = new FileInfo(filename); //string ftpServerIP = "ftp://146.0.229.66/AppMiddlePic/1" + objFile.Extension; //string ftpUserName = "******"; //string ftpPassword = "******"; string ftpServerIP = "ftp://85.195.82.94/AMMusicFiles/ripper/AppMiddlePic/" + MaxId + objFile.Extension; string ftpUserName = "******"; string ftpPassword = "******"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpServerIP)); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUserName, ftpPassword); request.UseBinary = true; request.UsePassive = false; byte[] fileStream = System.IO.File.ReadAllBytes(filename); System.IO.Stream requestStream = request.GetRequestStream(); for (int offset = 0; offset <= fileStream.Length; offset += 1024) { bgMiddleImage.ReportProgress(Convert.ToInt32(offset * pBarImage.Maximum / fileStream.Length)); int chSize = fileStream.Length - offset; if (chSize > 1024) { chSize = 1024; } requestStream.Write(fileStream, offset, chSize); } requestStream.Close(); requestStream.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } }
/// <summary> /// 获取网页HTML内容 /// </summary> /// <param name="Url">URL地址</param> /// <param name="Enc">字符编码</param> /// <returns></returns> public static string Get(string Url, Encoding Enc) { string respHTML = ""; try { System.Net.HttpWebRequest httpReq; System.Net.HttpWebResponse httpResp; System.Uri httpURL = new System.Uri(Url); httpReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL); httpReq.Method = "GET"; httpReq.KeepAlive = false; httpReq.ContentType = "text/html"; httpReq.Timeout = 30000; httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse(); using (System.IO.Stream MyStream = httpResp.GetResponseStream()) { System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8); //byte[] TheBytes = new byte[MyStream.Length]; //MyStream.Read(TheBytes, 0, (int)MyStream.Length); //respHTML = Encoding.UTF8.GetString(TheBytes); respHTML = reader.ReadToEnd(); reader.Dispose(); MyStream.Dispose(); } httpResp.Close(); httpReq = null; } catch (Exception ex) { throw new Exception("获取HTML发生异常:" + ex.Message); //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url); //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")"); } return(respHTML); }
public Gdk.Pixbuf GetImage(IProject project) { if (image != null) { return(image); } switch (source) { case ImageSource.Resource: if (project.ResourceProvider == null) { return(null); } System.IO.Stream s = project.ResourceProvider.GetResourceStream(name); if (s == null) { return(null); } try { return(image = new Gdk.Pixbuf(s)); } catch { // Not a valid image return(WidgetUtils.MissingIcon); } finally { s.Dispose(); } case ImageSource.Theme: return(image = WidgetUtils.LoadIcon(name, size)); case ImageSource.File: try { string file = Path.Combine(project.ImagesRootPath, name); return(image = new Gdk.Pixbuf(file)); } catch { return(WidgetUtils.MissingIcon); } } return(null); }
public static Result UploadFile(FTPConnectionInfo connectionInfo, string localFileName, string remoteFileName) { Result result = new Result(); string ftpFileName = string.Format("ftp://{0}/{1}", connectionInfo.ServerName, remoteFileName); FileInfo fileInfo = new FileInfo(localFileName); System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpFileName)); ftpWebRequest.Credentials = new System.Net.NetworkCredential(connectionInfo.Username, connectionInfo.Password); ftpWebRequest.KeepAlive = false; ftpWebRequest.Timeout = 20000; ftpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftpWebRequest.UseBinary = true; ftpWebRequest.ContentLength = fileInfo.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; System.IO.FileStream fileStream = fileInfo.OpenRead(); try { System.IO.Stream stream = ftpWebRequest.GetRequestStream(); int contentLen = fileStream.Read(buff, 0, buffLength); while (contentLen != 0) { stream.Write(buff, 0, contentLen); contentLen = fileStream.Read(buff, 0, buffLength); } stream.Close(); stream.Dispose(); fileStream.Close(); fileStream.Dispose(); } catch (Exception e) { result.Error.Code = ErrorCode.UPLOAD_FTP_FAIL; result.Error.Description = e.Message; } return(result); }
public override void SetImage(System.IO.Stream _p0) { // NOTICE: your responsibility to call Dispose() method on the given Stream(s) before you return from this statement or later on an other thread. try { // you may use this try-finally pattern and take your code here LOGGER.Info("TestContractServiceImpl.SetImage, size: " + (_p0 == null ? "<null>" : _p0.Length.ToString())); } finally { if (_p0 != null) { _p0.Dispose(); } } if (_p0 == null) { throw new Exception("Test exception."); } //throw new System.NotImplementedException(); }