private static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[32768]; while (true) { int read = input.Read(buffer, 0, buffer.Length); if (read <= 0) return; output.Write(buffer, 0, read); } }
public Block (System.IO.Stream stream) { this.stream = stream; Start = stream.Position; name = new byte [4]; byte [] tmp = new byte [8]; stream.Read (tmp, 0, tmp.Length); System.Array.Copy (tmp, name, name.Length); //System.Console.WriteLine (this.Name); Length = BitConverter.ToUInt32 (tmp, name.Length, false); stream.Position = stream.Position + Length; }
public GMKIn(System.IO.Stream source) { s = source; int tpos = (int)s.Position; len = (int)s.Length; s.Seek(0, System.IO.SeekOrigin.Begin); s.Read(buffer, 0, 16); int junk1 = BitConverter.ToInt32(buffer, 8); int junk2 = BitConverter.ToInt32(buffer, 12); s.Seek(junk1 * 4, System.IO.SeekOrigin.Current); s.Read(buffer, 8, 4); int seed = BitConverter.ToInt32(buffer, 8); table = GenerateSwapTable(seed); s.Seek(junk2 * 4, System.IO.SeekOrigin.Current); outlen = s.Length - (s.Position - 8L); outpos = 0; buffer[8] = (byte)s.ReadByte(); bufferptrin = 9; bufferptrout = tpos; pos = (int)s.Position; }
private void DirectToolStripMenuItem1_Click(object sender, EventArgs e) { var file = new OpenFileDialog(); file.DefaultExt = "mpdirect"; file.Filter = "MacroPad Direct files (*.mpdirect)|*.mpdirect"; if (file.ShowDialog() == DialogResult.OK) { listBoxOverride.Items.Clear(); OverrideList.Clear(); System.IO.Stream fstream = file.OpenFile(); byte[] cache = new byte[Override.sizeOf]; long count = fstream.Length / Override.sizeOf; for (int i = 0; i < count; i++) { fstream.Read(cache, 0, Override.sizeOf); OverrideList.Add(new Override(cache)); listBoxOverride.Items.Add(OverrideList.Last().ToString()); } fstream.Close(); fstream.Dispose(); } }
void NextDWord() { _Offset += 4; if (_Offset >= _BufferLength) { if (_BufferLength == _Buffer.Length) { _BufferLength = (int)_Stream.Read(_Buffer, 0, _Buffer.Length); if (_BufferLength < 0) { _BufferLength = 0; _EndOfStream = true; } else { _Offset = 0; } } else { _EndOfStream = true; } } }
bool FillBuffer() { if (charBuffer.Count == 0) { if (byteBuffer.Count == 0) { byteBuffer.Clear(); stream.Read(byteBuffer); } if (byteBuffer.Count > 0) { if (beginOfStream) { // Detect encoding // Check preamble } int bytesUsed; int charsUsed; decoder.Convert(byteBuffer, charBuffer, out bytesUsed, out charsUsed); } } return(charBuffer.Count > 0); }
/// <summary> /// Reads data from a stream until the end is reached. The /// data is returned as a byte array. An IOException is /// thrown if any of the underlying IO calls fail. /// </summary> /// <param name="stream">The stream to read data from</param> public static byte[] ReadFromStream(System.IO.Stream stream) { int read = 0; byte[] buffer = new byte[32768], ret = null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { while (true) { read = stream.Read(buffer, 0, buffer.Length); if (read <= 0) { ret = ms.ToArray(); break; } ms.Write(buffer, 0, read); } } return(ret); }
/// <summary> /// رمز گذاری استریم /// </summary> /// <param name="inputStream">استریم مورد نظر</param> /// <param name="outputStream">استریمی که رمز گذاری شود</param> /// <param name="Key">Key</param> /// <param name="IV">IV</param> public void Encrypt(System.IO.Stream inputStream, System.IO.Stream outputStream, byte[] Key, byte[] IV) { System.Security.Cryptography.CryptoStream _CryptoStream; if (Key == null && IV == null) { _CryptoStream = new System.Security.Cryptography.CryptoStream(outputStream, DES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write); } else { _CryptoStream = new System.Security.Cryptography.CryptoStream(outputStream, DES.CreateEncryptor(Key, IV), System.Security.Cryptography.CryptoStreamMode.Write); } int readCount = 0; byte[] Data = new byte[2048]; do { readCount = inputStream.Read(Data, 0, 2048); _CryptoStream.Write(Data, 0, readCount); }while (readCount > 0); _CryptoStream.FlushFinalBlock(); _CryptoStream.Close(); _CryptoStream.Dispose(); }
public static FontFamily LoadFont(string Fontname) { FontFamily font = null; try { string asmName = Assembly.GetName().Name.Replace(" ", "_"); using (System.IO.Stream s = Assembly.GetManifestResourceStream(asmName + ".Resources." + Fontname + ".ttf")) { System.IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)s.Length); byte[] data = new byte[(int)s.Length]; s.Read(data, 0, (int)s.Length); System.Runtime.InteropServices.Marshal.Copy(data, 0, ptr, data.Length); mFontColection.AddMemoryFont(ptr, data.Length); font = new FontFamily(mFontColection.Families[mFontColection.Families.Length - 1].Name, mFontColection); System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr); } return(font); } catch { return(null); } }
static bool LoadDll(string path) { Assembly curAssm = Assembly.GetExecutingAssembly(); string appName = curAssm.GetName().Name.Replace(" ", "_"); Assembly dllAssm = null; byte[] dllData; using (System.IO.Stream s = curAssm.GetManifestResourceStream($"{appName}.{path}")) { if (s != null) { dllData = new byte[s.Length]; s.Read(dllData, 0, (int)s.Length); dllAssm = Assembly.Load(dllData); } else { return(false); } } dict.Add(dllAssm.FullName, dllAssm); return(true); }
protected override System.IO.Stream OpenStream(string assetName) { // Check if data has been cached byte[] assetData = null; if (cachedAssetData.TryGetValue(assetName, out assetData)) { // read the asset data in first time if (assetData == null) { System.IO.Stream strm = base.OpenStream(assetName); assetData = new byte[strm.Length]; strm.Read(assetData, 0, (int)strm.Length); strm.Close(); cachedAssetData[assetName] = assetData; } // Every time a cached asset is requested, return memory stream return(new System.IO.MemoryStream(assetData)); } return(base.OpenStream(assetName)); }
private void btnExport_Click(object sender, RoutedEventArgs e) { if (list == null || list.Count == 0) { return; } ExportingModel export = new ExportingModel(); export.SelectedExportFormat = "Excel"; Assembly assembly = GetType().Assembly; string html = string.Empty; using (System.IO.Stream htmlStream = assembly.GetManifestResourceStream("PoliceSMS.HeaderTemplate.OfficerHeader.htm")) { byte[] bsHtml = new byte[htmlStream.Length]; htmlStream.Read(bsHtml, 0, (int)htmlStream.Length); html = Encoding.UTF8.GetString(bsHtml, 0, bsHtml.Length); } gvtmp.ItemsSource = list; export.ExportWithHeader(gvtmp, html); }
// 线程不安全,需要外面更大的锁保护。 public void UnSerializeFrom(System.IO.Stream stream) { if (Snapshoting) { throw new Exception("Coucurrent Error: In Snapshoting"); } Map.Clear(); for (int count = ReadInt4From(stream); count > 0; --count) { int kvsize = ReadInt4From(stream); var kvbytes = new byte[kvsize]; stream.Read(kvbytes); var bb = ByteBuffer.Wrap(kvbytes); K key = SerializeHelper <K> .Decode(bb); V value = new V(); value.Decode(bb); Map.TryAdd(key, value); // ignore result } }
/// <summary> /// 获取传入流 /// </summary> /// <returns></returns> public static string GetInputStream(this HttpRequest request) { try { System.IO.Stream stream = request.Body; bool isContentLength = request.ContentLength.HasValue; if (isContentLength) { byte[] buffer = new byte[request.ContentLength.Value]; stream.Read(buffer, 0, buffer.Length); string content = Encoding.UTF8.GetString(buffer); return(content); } else { return(string.Empty); } } catch (Exception ex) { throw new Exception(ex.Message); } }
// 標準入力から読み込む private static byte[] read_stdin() { int readlen = 0; byte[] buf = new byte[10 * 1024]; // 適当に最大 System.IO.Stream stdin = Console.OpenStandardInput(); while (true) { byte[] buffer = new byte[8]; // 1回分 int len = stdin.Read(buffer, 0, buffer.Length); if (len == 0) { break; } Array.Copy(buffer, 0, buf, readlen, len); readlen += len; } byte[] ret = new byte[readlen]; Array.Copy(buf, ret, readlen); return(ret); }
public static ZipEntry Read(System.IO.Stream s) { ZipEntry entry = new ZipEntry(); if (!ReadHeader(s, entry)) { return(null); } entry.__filedata = new byte[entry._CompressedSize]; int n = s.Read(entry._FileData, 0, entry._FileData.Length); if (n != entry._FileData.Length) { throw new Exception("badly formatted zip file."); } // finally, seek past the (already read) Data descriptor if necessary if ((entry._BitField & 0x0008) == 0x0008) { s.Seek(16, System.IO.SeekOrigin.Current); } return(entry); }
private void button_fly_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { button_fly.Enabled = false; System.IO.Stream file = openFileDialog1.OpenFile(); byte[] file_buf = new byte[file.Length]; file.Read(file_buf, 0, (int)file.Length); file.Close(); string file_string = System.Text.Encoding.Default.GetString(file_buf); string[] lines = file_string.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); commands.Clear(); foreach (string line in lines) { string[] param = line.Split(' '); commands.Add(new Command(int.Parse(param[0]), float.Parse(param[1]), float.Parse(param[2]), float.Parse(param[3]))); } Thread th1 = new Thread(SequenceThread); th1.Start(); } }
public FilterStatus Filter(System.IO.Stream dataIn, out long dataInRead, System.IO.Stream dataOut, out long dataOutWritten) { if (dataIn == null) { dataInRead = 0; dataOutWritten = 0; return(FilterStatus.Done); } dataInRead = dataIn.Length; dataOutWritten = Math.Min(dataInRead, dataOut.Length); byte[] buffer = new byte[dataOutWritten]; int bytesRead = dataIn.Read(buffer, 0, (int)dataOutWritten); dataOut.Write(buffer, 0, bytesRead); string s = System.Text.Encoding.UTF8.GetString(buffer); SaveContent(Entity, s);//写入文件 return(FilterStatus.Done); }
public ActionResult Create(Contact contact, FullName name, FullAddress ha, System.Web.HttpPostedFileBase image) { if (ModelState.IsValid) { BranchContext branchDb = new BranchContext("b-" + contact.BranchID); var personID = (Guid)Session["id"]; var person = branchDb.People.Find(personID); contact.ID = Guid.NewGuid(); ha.ID = Guid.NewGuid(); contact.Person = person; contact.Name = name; contact.HomeAddress = ha; ha.PersonID = contact.ID; if (image != null) { System.IO.Stream imgStream = image.InputStream; int size = (int)imgStream.Length; byte[] imgBytes = new byte[size]; imgStream.Read(imgBytes, 0, size); contact.Picture = imgBytes; } else { contact.Picture = new byte[] { 0 }; } branchDb.Contacts.Add(contact); branchDb.FullAddresses.Add(ha); branchDb.SaveChanges(); // save changes to the database return(RedirectToAction("Index", new { id = personID })); } ViewBag.BranchID = new SelectList(db.Branches, "ID", "Name", contact.BranchID); return(View(contact)); }
/// <summary> /// Deserializes a tags index from the given stream. /// </summary> public static AttributesIndex Deserialize(System.IO.Stream stream, bool copy = false) { var type = stream.ReadByte(); long size; if (type == 0) { var tagsIndex = Index <int[]> .CreateFromWithSize(stream, out size, !copy); var totalSize = size + 8 + 1; stream.Seek(totalSize, System.IO.SeekOrigin.Begin); var limitedStream = new LimitedStream(stream); var stringIndex = Index <string> .CreateFromWithSize(limitedStream, out size, !copy); totalSize += size + 8; stream.Seek(totalSize, System.IO.SeekOrigin.Begin); return(new AttributesIndex(stringIndex, tagsIndex)); } else { var tagsIndex = Index <int[]> .CreateFromWithSize(stream, out size, !copy); var totalSize = size + 8 + 1; stream.Seek(totalSize, System.IO.SeekOrigin.Begin); var limitedStream = new LimitedStream(stream); var stringIndex = Index <string> .CreateFromWithSize(limitedStream, out size, !copy); totalSize += size + 8; stream.Seek(totalSize, System.IO.SeekOrigin.Begin); var indexLengthBytes = new byte[8]; stream.Read(indexLengthBytes, 0, 8); var indexLength = BitConverter.ToInt64(indexLengthBytes, 0); var index = new MemoryArray <uint>(indexLength); index.CopyFrom(stream); return(new AttributesIndex(stringIndex, tagsIndex, index)); } }
private void getPurCom() { try { DataTable dt_ = new DataTable(); dt_ = Get_CompPur(); cryRpt.Load(Server.MapPath("rpt_pur_ComWise.rpt")); cryRpt.SetDatabaseLogon("sa", "friend", "ASAD-PC", "OrionFoods"); cryRpt.SetDataSource(dt_); //cryRpt.RecordSelectionFormula = cryRpt.SetParameterValue("Report Name", "Comapny Wise Purchase Report"); //cryRpt.SetParameterValue("Report Name", "Purchase Report"); //cryRpt.SetParameterValue("ComName", "Orion Foods"); System.IO.Stream oStream = null; byte[] byteArray = null; oStream = cryRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); byteArray = new byte[oStream.Length]; oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1)); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.BinaryWrite(byteArray); Response.Flush(); Response.Close(); cryRpt.Close(); cryRpt.Dispose(); //rprt.Load(Server.MapPath("~/CrystalReport.rpt")); } catch (Exception ex) { throw ex; } }
private static Assembly resolve(object sender, ResolveEventArgs args) { string dllName = new AssemblyName(args.Name).Name + ".dll"; var assembly = Assembly.GetExecutingAssembly(); string resourceName = assembly.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName)); if (resourceName == null) { return(null); // Not found, maybe another handler will find it } System.IO.Stream stream = null; Assembly loadedAssembly = null; try { stream = assembly.GetManifestResourceStream(resourceName); byte[] assemblyData = new byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); loadedAssembly = Assembly.Load(assemblyData); } catch (Exception Ex) { loadedAssembly = null; Shutdown("DLL", Ex); } finally { if (stream != null) { stream.Dispose(); } } return(loadedAssembly); }
///// <summary> ///// Get values from WebAccess, not useable yet ///// </summary> ///// <param name="tagName"></param> ///// <returns></returns> //public string[] GetValueText(string[] tagName) { // m_ErrMsg = ""; // string[] result = new string[tagName.Length]; // TagValueParamObj tagValueParamObj = new TagValueParamObj(); // TagValueParam valParam; // for (int i = 0; i < tagName.Length; i++) { // valParam = new TagValueParam(tagName[i]); // tagValueParamObj.Tags.Add(valParam); // } // string paramStr = JSONHelper.serialise(tagValueParamObj); // byte[] reqBodyBytes = Encoding.UTF8.GetBytes(paramStr); // HttpWebRequest request = (HttpWebRequest)WebRequest.Create( // "http://" + m_serverip + "/WaWebService/Json/GetTagValueText/" + m_Proj); // request.ContentType = "application/json"; // request.Method = WebRequestMethods.Http.Post; // request.Headers["Authorization"] = m_Authorization; // System.IO.Stream reqStream = request.GetRequestStream(); // reqStream.Write(reqBodyBytes, 0, reqBodyBytes.Length); // reqStream.Close(); // try { // HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // System.IO.Stream resStream = response.GetResponseStream(); // byte[] buff = new byte[response.ContentLength]; // resStream.Read(buff, 0, (int)response.ContentLength); //resStream.Length // string resStr = Encoding.UTF8.GetString(buff); // } catch (WebException ex) { // ; // } // return result; //} public bool SetValueText(string tagName, string tagValue) { m_ErrMsg = ""; TagValueParamObj tagValueParamObj = new TagValueParamObj(); tagValueParamObj.Tags.Add(new TagValueParam(tagName, tagValue)); string paramStr = JSONHelper.serialise(tagValueParamObj); byte[] reqBodyBytes = Encoding.UTF8.GetBytes(paramStr); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + m_serverip + "/WaWebService/Json/SetTagValueText/" + m_Proj); request.ContentType = "application/json"; request.Method = WebRequestMethods.Http.Post; request.Headers["Authorization"] = m_Authorization; System.IO.Stream reqStream = request.GetRequestStream(); reqStream.Write(reqBodyBytes, 0, reqBodyBytes.Length); reqStream.Close(); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream resStream = response.GetResponseStream(); byte[] buff = new byte[response.ContentLength]; resStream.Read(buff, 0, (int)response.ContentLength); string resStr = Encoding.UTF8.GetString(buff); if (resStr != "{\"Ret\":0}") { m_ErrMsg = "Failed"; return(false); } } catch (WebException ex) { m_ErrMsg = ex.Message; return(false); } return(true); }
/// <summary> /// 接收从微信支付后台发送过来的数据并验证签名 /// </summary> /// <returns>微信支付后台返回的数据</returns> public WxPayData GetNotifyData() { //接收从微信后台POST过来的数据 System.IO.Stream s = System.Web.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(); PayLogHelper.Debug("WX:" + 1111); //转换数据格式并验证签名 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); PayLogHelper.Debug("WX:若签名错误" + "Sign check error : " + res.ToXml()); } PayLogHelper.Debug("WX:Check sign success"); return(data); }
/// <summary> /// Inflates all the recognizable metadata from a .CFG file from the given stream. /// </summary> /// <param name="stream">The stream containing the data to parse for CFGVAR metadata.</param> /// <returns>An enumerable of the recognizable metadata.</returns> /// <remarks>Callers should be dutiful in handling exceptions, as stream, Regex and other exceptions may result during parsing. /// Also note that this is a really simplistic parser, so it's possible that all sorts of holes exist.</remarks> public static IEnumerable <CfgVarMetadataBlock> InflateAll(System.IO.Stream stream) { var metadataBlocks = new List <CfgVarMetadataBlock>(); var cfgFileSize = (int)stream.Length; var cfgFileBytes = new byte[cfgFileSize]; if (stream.Read(cfgFileBytes, 0, cfgFileSize) == cfgFileSize) { var cfgFileContents = System.Text.Encoding.UTF8.GetString(cfgFileBytes, 0, cfgFileBytes.Length).Trim('\0'); var cfgFileLines = cfgFileContents.Split(new[] { "\n", "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries); var currentSection = string.Empty; const string VarsSection = "[vars]"; foreach (var cfgFileLine in cfgFileLines) { var sectionMatch = Regex.Match(cfgFileLine, @"\[(.*?)\]"); if (sectionMatch.Success) { currentSection = sectionMatch.Value; } else if (currentSection.Equals(VarsSection, StringComparison.OrdinalIgnoreCase)) { var cfgFileLineBytes = System.Text.Encoding.UTF8.GetBytes(cfgFileLine); using (var cfgFileLineStream = new System.IO.MemoryStream(cfgFileLineBytes)) { var metadataBlock = CfgVarMetadataBlock.Inflate(cfgFileLineStream); if (metadataBlock != null) { metadataBlocks.Add(metadataBlock); } } } } } return(metadataBlocks); }
/// <summary> /// 接收从微信支付后台发送过来的数据并验证签名 /// </summary> /// <returns>微信支付后台返回的数据</returns> public WxPayData GetNotifyData() { //接收从微信后台POST过来的数据 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(); LogService.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); LogService.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml()); } LogService.Info(this.GetType().ToString(), "Check sign success"); return(data); }
/// <summary> /// 接收从微信支付后台发送过来的数据并验证签名 /// </summary> /// <returns>微信支付后台返回的数据</returns> public WxPayData GetNotifyData() { //接收从微信后台POST过来的数据 System.IO.Stream s = page.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); page.Response.Write(res.ToXml()); page.Response.End(); } return(data); }
public static PixelBuffer LoadImageFromBuffer(System.IO.Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } long streamLength = stream.Length - stream.Position; if (streamLength <= 0) { throw new InvalidOperationException("stream lenght is <= 0"); } // Read data from stream byte[] streamData = new byte[streamLength]; stream.Read(streamData, 0, (int)streamLength); // Allocate buffer that internal DALi engine can read VectorUnsignedChar buffer = new VectorUnsignedChar(); buffer.Resize((uint)streamLength); var bufferBegin = buffer.Begin(); global::System.Runtime.InteropServices.HandleRef bufferRef = SWIGTYPE_p_unsigned_char.getCPtr(bufferBegin); // Copy data from stream to buffer System.Runtime.InteropServices.Marshal.Copy(streamData, 0, bufferRef.Handle, (int)streamLength); PixelBuffer ret = new PixelBuffer(Interop.ImageLoading.LoadImageFromBuffer(VectorUnsignedChar.getCPtr(buffer)), true); buffer.Dispose(); if (NDalicPINVOKE.SWIGPendingException.Pending) { throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public bool AddFile(string localFilePath, int roomId) { var roomsApi = getRoomsApi(); string fileId = null; int maxFileSize = 10000000; // bytes.. 10 MB System.IO.FileInfo fi = new System.IO.FileInfo(localFilePath); if (!fi.Exists) { _lastError = "File doesn't exist."; } else if (fi.Length > maxFileSize) { _lastError = "File size cannot be greater than " + maxFileSize + " bytes."; } else { string fileName = fi.Name; byte[] fileContent = new byte[fi.Length]; System.IO.Stream str = fi.OpenRead(); str.Read(fileContent, 0, Convert.ToInt32(fi.Length)); string fileData = Convert.ToBase64String(fileContent); var result = roomsApi.PostFile(getAuthHeader(), roomId, 0, fileName, fileData); if (result.success && result.data != null) { fileId = result.data.ToString(); } else { _lastError = result.code.ToString(); } str.Close(); str.Dispose(); } return(fileId != null); }
public int Read(byte[] buffer, uint cb, out uint cbRead) { cbRead = 0; #pragma warning disable 6500 try { Verify(); ActualizeVirtualPosition(); cbRead = (uint)dataStream.Read(buffer, 0, (int)cb); } catch (Exception e) { // store the last exception _lastException = e; return(SecurityHelper.GetHRForException(e)); } #pragma warning restore 6500 return(NativeMethods.S_OK); }
////////////////////////////////////////////////////////////////////////// // Handlers ////////////////////////////////////////////////////////////////////////// private void inHandler() { System.IO.Stream input = SysInStream.dotnet(m_in); System.IO.Stream output = m_proc.StandardInput.BaseStream; byte[] temp = new byte[256]; while (!m_proc.HasExited) { try { int n = input.Read(temp, 0, temp.Length); if (n < 0) { break; } output.Write(temp, 0, n); output.Flush(); } catch (System.Exception e) { Err.dumpStack(e); } } }
/// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary> /// <param name="sourceStream">The source Stream to read from.</param> /// <param name="target">Contains the array of characteres read from the source Stream.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source Stream.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.IO.Stream sourceStream, sbyte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) { return(0); } byte[] receiver = new byte[target.Length]; int bytesRead = sourceStream.Read(receiver, start, count); // Returns -1 if EOF if (bytesRead == 0) { return(-1); } for (int i = start; i < start + bytesRead; i++) { target[i] = (sbyte)receiver[i]; } return(bytesRead); }
public System.Reflection.Assembly Load(AppDomain appDomain, System.IO.Stream assemblyStream, int length) { byte[] buffer = new byte[length]; int offset = 0; while (length > 0) { int num3 = assemblyStream.Read(buffer, offset, length); if (num3 == 0) { break; } offset += num3; length -= num3; } if (appDomain != null) { return(appDomain.Load(buffer)); } else { return(System.Reflection.Assembly.Load(buffer)); } }
public ImageDirectory (System.IO.Stream stream, uint start, long end, bool little) { this.start = start; this.little = little; this.stream = stream; entry_list = new System.Collections.ArrayList (); stream.Position = end - 4; byte [] buf = new byte [10]; stream.Read (buf, 0, 4); uint directory_pos = BitConverter.ToUInt32 (buf, 0, little); DirPosition = start + directory_pos; stream.Position = DirPosition; stream.Read (buf, 0, 2); Count = BitConverter.ToUInt16 (buf, 0, little); for (int i = 0; i < Count; i++) { stream.Read (buf, 0, 10); System.Console.WriteLine ("reading {0} {1}", i, stream.Position); Entry entry = new Entry (buf, 0, little); entry_list.Add (entry); } }
/// <summary> /// Copies a stream to a Glacier vault archive /// </summary> /// <param name="stream"> /// The stream to read /// </param> /// <returns> /// The total number of bytes read /// </returns> public Int64 Upload(Stream stream) { var streamLength = 0L; for (; ; ) { // if we have filled the current part, then upload it if (this.partOffset == PartSize) Flush(); // read the next block from the input stream var read = stream.Read( this.readBuffer, 0, Math.Min( this.readBuffer.Length, PartSize - this.partOffset ) ); if (read == 0) break; // write the results to the part buffer stream this.partStream.Write(this.readBuffer, 0, read); this.partOffset += read; streamLength += read; } return streamLength; }