public int DecryptFile(string filePath) { byte[] result; string path = filePath.Substring(0, filePath.Length - 4); using (System.IO.FileStream x = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read), decWriter = new System.IO.FileStream(path, System.IO.FileMode.Append)) using (System.IO.BinaryReader y = new System.IO.BinaryReader(x)) { long numBytes = new System.IO.FileInfo(filePath).Length; int loops = (int)(numBytes / (1048576 + 16)); for (int i = 0; i <= loops; i++) { if (i == loops) { if (_AESCP.Decrypt(y.ReadBytes((int)(numBytes % (1048576 + 16))), out result) != CRYPTO_RESULT.SUCCESS) { return(-1); } decWriter.Write(result, 0, result.Length); decWriter.Flush(); break; } if (_AESCP.Decrypt(y.ReadBytes(1048576 + 16), out result) != CRYPTO_RESULT.SUCCESS) { return(-1); } decWriter.Write(result, 0, result.Length); decWriter.Flush(); } return(0); } }
static int _m_Flush(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.FileStream gen_to_be_invoked = (System.IO.FileStream)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if (gen_param_count == 1) { gen_to_be_invoked.Flush( ); return(0); } if (gen_param_count == 2 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 2)) { bool _flushToDisk = LuaAPI.lua_toboolean(L, 2); gen_to_be_invoked.Flush(_flushToDisk); return(0); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } return(LuaAPI.luaL_error(L, "invalid arguments to System.IO.FileStream.Flush!")); }
public void Write(string message, LogLevel level) { lock (_lock) { byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(message + "\r\n"); fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(); } }
public override void Flush() { lock (lockFile) { if (fs != null) { fs.Flush(); } } }
void bdsEmployee_PositionChanged(object sender, EventArgs e) { drCurrent = ((DataRowView)bdsEmployee.Current).Row; bdsThue.Filter = "Ma_CbNv = '" + drCurrent["Ma_CbNv"] + "'"; object objPic = SQLExec.ExecuteReturnValue("SELECT Hinh FROM LINHANVIEN WHERE Ma_CbNv = '" + (string)drCurrent["Ma_CbNv"] + "'"); Byte[] bytePic = (Byte[])objPic; if (objPic != null && objPic != DBNull.Value && bytePic.Length != 0) { byte[] barrImg = bytePic; string strFileName = Convert.ToString(DateTime.Now.ToFileTime()); System.IO.FileStream fs = new System.IO.FileStream(strFileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); fs.Write(barrImg, 0, barrImg.Length); fs.Flush(); fs.Close(); picHinh.Image = Image.FromFile(strFileName); picHinh.SizeMode = PictureBoxSizeMode.Zoom; } else { picHinh.Image = null; } }
private void WriteModifications(string dataHistoryFile, IIntegrationResult result) { System.IO.FileStream fs = new System.IO.FileStream(dataHistoryFile, System.IO.FileMode.Append); fs.Seek(0, System.IO.SeekOrigin.End); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); System.Xml.XmlTextWriter currentBuildInfoWriter = new System.Xml.XmlTextWriter(sw); currentBuildInfoWriter.Formatting = System.Xml.Formatting.Indented; currentBuildInfoWriter.WriteStartElement("Build"); WriteXMLAttributeAndValue(currentBuildInfoWriter, "BuildDate", Util.DateUtil.FormatDate(result.EndTime)); WriteXMLAttributeAndValue(currentBuildInfoWriter, "Success", result.Succeeded.ToString(CultureInfo.CurrentCulture)); WriteXMLAttributeAndValue(currentBuildInfoWriter, "Label", result.Label); if (result.Modifications.Length > 0) { currentBuildInfoWriter.WriteStartElement("modifications"); for (int i = 0; i < result.Modifications.Length; i++) { result.Modifications[i].ToXml(currentBuildInfoWriter); } currentBuildInfoWriter.WriteEndElement(); } currentBuildInfoWriter.WriteEndElement(); sw.WriteLine(); sw.Flush(); fs.Flush(); sw.Close(); fs.Close(); }
} // End Sub Main public static void CompressFile(string FileToCompress, string CompressedFile) { //byte[] buffer = new byte[1024 * 1024 * 64]; byte[] buffer = new byte[1024 * 1024]; // 1MB using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress)) { using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile)) { using (System.IO.Compression.GZipStream output = new System.IO.Compression.GZipStream(destinationFile, System.IO.Compression.CompressionMode.Compress)) { int bytesRead = 0; while (bytesRead < sourceFile.Length) { int ReadLength = sourceFile.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, ReadLength); output.Flush(); bytesRead += ReadLength; } // Whend destinationFile.Flush(); } // End Using System.IO.Compression.GZipStream output destinationFile.Close(); } // End Using System.IO.FileStream destinationFile // Close the files. sourceFile.Close(); } // End Using System.IO.FileStream sourceFile } // End Sub CompressFile
public void Flush() { if (null != fzblock) { fzblock.Flush(); } }
private void ProcessStep2(string FileName) { Random Rand = new Random(DateTime.Now.Millisecond); ASCIIEncoding c = new ASCIIEncoding(); byte RandI = c.GetBytes(Microsoft.VisualBasic.Strings.Chr(Rand.Next(33, 255)).ToString())[0]; System.IO.FileStream fs = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); if (fs.CanRead == true && fs.CanWrite == true) { try { byte[] b = new byte[Convert.ToInt32(fs.Length - 1) + 1]; for (int i = 0; i <= Convert.ToInt32(fs.Length - 1); i++) { b[i] = RandI; } fs.Write(b, 0, Convert.ToInt32(fs.Length - 1)); fs.Flush(); } catch (Exception ex) { } finally { } } fs.Close(); }
public IActionResult UploadAjax() { string msg; bool success = false; try { long size = 0; var files = Request.Form.Files; foreach (var file in files) { var filename = System.Net.Http.Headers.ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = _env.WebRootPath + $@"\{filename}"; size += file.Length; using (System.IO.FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } msg = $"{files.Count} file(s) / {size} bytes uploaded successfully!"; success = true; } catch (Exception ex) { msg = ex.Message; } return(Json(new { success = success, msg = msg })); }
} // End Sub CreateHugeGzipFile private static void CreateHugeBullshitGzipFile() { if (System.IO.File.Exists(fileName)) { return; } byte[] buffer = new byte[ONE_MEGABYTE]; // 1MB using (System.IO.FileStream gzipTargetAsStream = System.IO.File.OpenWrite(fileName)) { using (System.IO.Compression.GZipStream gzipStream = new System.IO.Compression.GZipStream(gzipTargetAsStream, System.IO.Compression.CompressionLevel.Optimal)) { try { for (int i = 0; i < REPEAT_COUNT; ++i) { gzipStream.Write(buffer, 0, ONE_MEGABYTE); gzipStream.Flush(); gzipTargetAsStream.Flush(); } // Next i } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); } } // End Using GZipStream } // End Using gzipTargetAsStream } // End Sub CreateHugeBullshitGzipFile
private void btnBrowse_Click(object sender, EventArgs e) { opnPic.Filter = "(PNG File )|*.png"; if (opnPic.ShowDialog() == DialogResult.Cancel) { //return; } else { System.IO.FileStream picstream = new System.IO.FileStream(opnPic.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); using (Image img = Image.FromStream(picstream)) { //Image img; //img1 = Image.FromStream(picstream); Bitmap img1 = new Bitmap(img); pic.Image = img1; lblFilename.Text = opnPic.FileName.ToString(); img1 = null; picstream.Flush(); picstream = null; GC.Collect(); } } }
private void DrawDebugRenderTargets() { _sb.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointWrap, DepthStencilState.None, RasterizerState.CullNone); _sb.Draw(_albedoTarget, new Rectangle(0, 0, _albedoTarget.Width / 5, _albedoTarget.Height / 5), Color.White); _sb.Draw(_lightTarget, new Rectangle(_albedoTarget.Width / 5, 0, _lightTarget.Width / 5, _lightTarget.Height / 5), Color.White); _sb.Draw(_normalTarget, new Rectangle(_albedoTarget.Width / 5 + _lightTarget.Width / 5, 0, _normalTarget.Width / 5, _normalTarget.Height / 5), Color.White); _sb.Draw(_randomMap, new Rectangle(_albedoTarget.Width / 5 + _lightTarget.Width / 5 + _normalTarget.Width / 5, 0, _randomMap.Width / 5, _randomMap.Height / 5), Color.White); if (Input.Input.Get().IsKeyDown(Keys.F5, true)) { System.IO.FileStream fs = System.IO.File.Create("pic.png"); _lightTarget.SaveAsPng(fs, _lightTarget.Width, _lightTarget.Height); fs.Flush(); fs.Close(); fs.Dispose(); } _sb.DrawString(_uiFontTiny, "Albedo", new Vector2(2, 2), Color.White); _sb.DrawString(_uiFontTiny, "Light", new Vector2(_albedoTarget.Width / 5 + 2, 2), Color.White); _sb.DrawString(_uiFontTiny, "Normal", new Vector2(_albedoTarget.Width / 5 + _lightTarget.Width / 5 + 2, 2), Color.White); _sb.DrawString(_uiFontTiny, "Depth", new Vector2(_albedoTarget.Width / 5 + _lightTarget.Width / 5 + _normalTarget.Width / 5 + 2, 2), Color.White); _sb.End(); }
public void Log2File(string msg) { string path = null, fullPath = null; GetPath(out path, out fullPath); if (System.IO.Directory.Exists(path) == false) { System.IO.Directory.CreateDirectory(path); } string date = System.DateTime.Now.ToString("yyyyMMdd HH:mm:ss"); string line = string.Format(System.Environment.NewLine + "[{0}]>>>{1}", date, msg); if (System.IO.File.Exists(fullPath)) { System.IO.FileStream stream = System.IO.File.OpenWrite(fullPath); System.Text.Encoding encoder = System.Text.Encoding.UTF8; byte[] bytes = encoder.GetBytes(line); stream.Position = stream.Length; stream.Write(bytes, 0, bytes.Length); stream.Flush(); stream.Close(); stream.Dispose(); } else { System.IO.StreamWriter writer = System.IO.File.CreateText(fullPath); writer.WriteLine(line); writer.Flush(); writer.Close(); writer.Dispose(); } }
public object Paste(Type type) { if (System.IO.File.Exists(file) == false) { return(null); } System.IO.Stream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); try { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); object instance = formater.Deserialize(stream); stream.Flush(); stream.Close(); return(instance); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); return(null); } finally { stream.Close(); } }
/// <summary> /// Кодирует обьект по умолчанию в кодировке ASCII. /// </summary> public void changingthecoding() { for (int i = 0; i < fileList.Count; i++) { System.IO.FileStream stream = fileStream(fileList[i]); byte[] buffer = new byte[4096]; byte[] newBuffer = new byte[4096]; while (stream.Position < stream.Length) { int count = stream.Read(buffer, 0, buffer.Length); for (int j = 0; j < count - 1; j++) { newBuffer = Encoding.ASCII.GetBytes(buffer[j] + " "); } stream.Write(newBuffer, 0, newBuffer.Length); stream.Flush(); } if (Messang != null) { Messang(this, new MyEvenArgs(string.Format("Объект '{0}' был изменен", fileList[i]))); } stream.Close(); } }
private void SaveFile(string file, IHttpContext context) { string path = AppDomain.CurrentDomain.BaseDirectory + $"views{System.IO.Path.DirectorySeparatorChar}files{System.IO.Path.DirectorySeparatorChar}"; if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } string filename = path + file; var data = System.Buffers.ArrayPool <byte> .Shared.Rent(context.Request.Length); try { context.Request.Stream.Read(data, 0, data.Length); using (System.IO.FileStream stream = System.IO.File.Open(filename, System.IO.FileMode.Create)) { stream.Write(data, 0, context.Request.Length); stream.Flush(); } } finally { System.Buffers.ArrayPool <byte> .Shared.Return(data); } }
public void CreateXml(ActiveRecordModel model) { CreateXmlPI(); StartMappingNode(); Ident(); VisitModel(model); Dedent(); EndMappingNode(); #if OUTPUTXML String file = model.Type.Name + ".maping.xml"; System.IO.File.Delete(file); using (System.IO.FileStream fs = System.IO.File.OpenWrite(file)) { String xml = Xml; byte[] ba = System.Text.ASCIIEncoding.UTF8.GetBytes(xml); fs.Write(ba, 0, ba.Length); fs.Flush(); } #endif }
public int SaveToFile(System.IO.FileStream fileStream, IFormatterResolver resolver) { lock (memories) { var bytes = new byte[255]; // buffer var size = 0; var offset = 0; offset += MessagePackBinary.WriteArrayHeader(ref bytes, 0, MemoryCount); fileStream.Write(bytes, 0, offset); // write header. size += offset; foreach (var item in memories) { offset = 0; offset += MessagePackBinary.WriteArrayHeader(ref bytes, offset, 2); offset += MessagePackBinary.WriteString(ref bytes, offset, item.Key); offset += item.Value.Serialize(ref bytes, offset, resolver); fileStream.Write(bytes, 0, offset); size += offset; } fileStream.Flush(); return(size); } }
public void Capture() { var screenshotPath = Android.OS.Environment.GetExternalStoragePublicDirectory("Pictures").AbsolutePath + Java.IO.File.Separator + "screenshot.png"; var rootView = ((Android.App.Activity)MainActivity.Context).Window.DecorView.RootView; using (var screenshot = Android.Graphics.Bitmap.CreateBitmap( rootView.Width, rootView.Height, Android.Graphics.Bitmap.Config.Argb8888)) { var canvas = new Android.Graphics.Canvas(screenshot); rootView.Draw(canvas); using (var screenshotOutputStream = new System.IO.FileStream( screenshotPath, System.IO.FileMode.Create)) { screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, screenshotOutputStream); screenshotOutputStream.Flush(); screenshotOutputStream.Close(); } } }
//sends the packet and deletes it when done (if successful).rv :true success public override bool send(netHeader.NetPacket pkt) { int writen = 0; Console.Error.WriteLine("---------------------Sent Packet"); PacketReader.EthernetFrame ef = new PacketReader.EthernetFrame(pkt); htapstream.Write(pkt.buffer, 0, pkt.size); htapstream.Flush(); //return type is void, assume full write writen = pkt.size; bool result = false; result = true; if (result) { if (writen != pkt.size) { Console.Error.WriteLine("Incompleat Send " + Marshal.GetLastWin32Error()); return(false); } return(true); } else { Console.Error.WriteLine("No Send Result" + Marshal.GetLastWin32Error()); return(false); } }
private void Options_CharCodeMap_Click(object sender, EventArgs e) { string sOut = "<html><head><title>GRebind - Charcode map</title>" + "\r\n" + "<style type=\"text/css\">" + "\r\n" + "body{ background: #fff; padding: 8px; color: #000; }" + "\r\n" + "table{ background: #eee; padding: 4px;" + "\r\n" + " border-color: #bbb; border-style: solid;" + "\r\n" + " border-width: 1px 1px 1px 1px; }" + "\r\n" + "td{ text-align: left; margin: 0px; padding: 4px;" + "\r\n" + " background-color: #fff; border-color: #ccc;" + "\r\n" + " border-width: 1px; border-style: solid; }" + "\r\n" + "</style></head><body>" + "\r\n" + "<center><h2>What's this for?</h2><p>" + "\r\n" + "If you want to emulate a key which you don't have, you will need the keycodes for the key to<br>" + "\r\n" + "assign to and the key to emulate. Once you know the keycodes, you can add the binding<br>" + "\r\n" + "by double-clicking the \"Mapped keys\" list and entering the keycodes manually.<br>" + "\r\n" + "<b>TIP: Press ctrl-f and enter the key's name.</b></p>" + "\r\n" + "<br><table cellspacing=4>" + "\r\n" + "\r\n" + "<tr><td>Keycode</td><td>Key</td></tr>" + "\r\n"; for (int a = 0; a < 255; a++) { sOut += "<tr><td>" + a + "</td><td>" + (Keys)a + "</td></tr>" + "\r\n"; } sOut += "\r\n" + "</table></center></body></html>"; byte[] bChars = System.Text.Encoding.UTF8.GetBytes(sOut); System.IO.FileStream fs = new System.IO.FileStream( "charmap.html", System.IO.FileMode.Create); fs.Write(bChars, 0, bChars.Length); fs.Flush(); fs.Close(); fs.Dispose(); System.Diagnostics.Process.Start("charmap.html"); }
/// <summary> /// Save the users list to a binary file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void menuSave_Click(object sender, RoutedEventArgs e) { // Need to create the binary formatter System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //Let the user pick where to save the file Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.Filter = "Data Files (*.dat)|*.dat|All Files (*.*)|*.*"; bool?dialogResult = sfd.ShowDialog(); //Only run if they hit the save button if ((bool)dialogResult) { try { //Create the instance of the file stream to write to System.IO.Stream stream = new System.IO.FileStream(sfd.FileName, System.IO.FileMode.OpenOrCreate); //serializes the data and sends it to the file stream formatter.Serialize(stream, users); //flush and close the stream stream.Flush(); stream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } //end catch } //end if }
/// <summary> /// Редактирование обьекта. /// </summary> public void editing() { for (int i = 0; i < fileList.Count; i++) { System.IO.FileStream stream = fileStream(fileList[i]); char a = 'a'; char b = '!'; { byte[] buffer = new byte[4096]; while (stream.Position < stream.Length) { int count = stream.Read(buffer, 0, buffer.Length); for (int j = 0; j < count; j++) { if (buffer[j] == (byte)a) { buffer[j] = (byte)b; } } stream.Write(buffer, 0, buffer.Length); stream.Flush(); } } messenger(fileList[i]); stream.Close(); } }
public bool EinstellungenSpeichernInDatei(string DateiName) { System.IO.FileStream outStream = null; System.IO.StreamWriter configStreamWriter = null; PlotterCom.StaticLogger.Log("Speichere Einstellungen in Datei ab.", 7); try { outStream = System.IO.File.Open(DateiName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read); configStreamWriter = new System.IO.StreamWriter(outStream); } catch (Exception ex) { PlotterCom.StaticLogger.Log("Kann Einstellungsdatei nicht zum schreiben öffnen!", 4); PlotterCom.StaticLogger.Log("Fehler: " + ex.Message, 4); return(false); } configStreamWriter.Write(ConfigStringErstellen()); configStreamWriter.Flush(); outStream.Flush(); configStreamWriter.Close(); outStream.Close(); return(true); }
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { if (grantResults.Length > 0 && grantResults[0] == (int)Permission.Granted) { switch (requestCode) { case REQUEST_STORAGE_FOR_BOOK: try { System.IO.Stream fis = Assets.Open("shei-shenghuo-de-geng-meihao.txt"); File outFile = new File(global::Android.OS.Environment.ExternalStorageDirectory, "/ChineseReader/shei-shenghuo-de-geng-meihao.txt"); System.IO.Stream fout = new System.IO.FileStream(outFile.Path, System.IO.FileMode.Create, System.IO.FileAccess.Write); CopyFile(fis, fout); fis.Close(); fout.Flush(); fout.Close(); } catch (Exception e) { System.Console.WriteLine("MainActivity OnRequestPermissionResult ERROR => " + e.Message); } break; case REQUEST_STORAGE_FOR_FILEBROWSER: OpenFileBrowser(); break; case REQUEST_STORAGE_FOR_SAVE: SaveToFile(); break; } } }
public static void Dump(string fileName, byte[] bytes) { System.IO.FileStream s = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate); s.Write(bytes, 0, bytes.Length); s.Flush(); s.Close(); }
private void btnSaveStream_Click(object sender, RoutedEventArgs e) { SaveFileDialog savefile = new SaveFileDialog() { Filter = "Pdf Document(*.Pdf)|*.Pdf", Title = "Save" }; bool?result = savefile.ShowDialog(); if (result.Value) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); //Pdf document to save the file stream. pdfViewer1.SaveToFile(stream); stream.Position = 0; byte[] fileBytes = stream.ToArray(); stream.Close(); System.IO.FileStream fileStream = new System.IO.FileStream(savefile.FileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); fileStream.Write(fileBytes, 0, fileBytes.Length); fileStream.Flush(); fileStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Fixed: /// </summary> private static void Save(PostedFile file, System.IO.FileInfo saveFile) { System.IO.FileStream saveFileStream = null; var en = Enumerable.Range(0, 100).ToArray(); foreach (var index in en) { try { saveFileStream = saveFile.Open(System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read); if (saveFileStream != null) { break; } } catch (System.IO.IOException) { if (index >= en.Last()) { throw; } } } using (saveFileStream) { file.InputStream.CopyTo(saveFileStream); saveFileStream.Flush(); } }
public static void Dump(string fileName, byte[] bytes) { System.IO.FileStream s = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate); s.Write(bytes, 0, bytes.Length); s.Flush(); s.Close(); }
public void UpdateData(string Phone) { try { var token = RSAHelper.Encrypt("ceshi").Replace("+", "%2B"); var postData = string.Format("Token={0}&Phone={1}", token, Phone); var msg = WebClientHelper.WebClientRequset(postData, "api/Updater/UpgradePrograms"); var obj = msg.FromJson <UpgradeProgramsModel>(); if (obj.StatusCode == 200) { //升级下来的名字 // string filename = System.IO.Path.Combine(Application.StartupPath, "易考星升级包.zip"); //下载下来的是一个压缩包数据流// System.IO.FileStream fs = new System.IO.FileStream(SqlDataRepertory.DB_Name, System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(Convert.FromBase64String(obj.Data.File), 0, Convert.FromBase64String(obj.Data.File).Length); fs.Flush(); fs.Close(); textViewTips.Text = "升级成功"; } else { textViewTips.Text = "升级失败,请检查网络连接"; } } catch (Exception ex) { textViewTips.Text = "升级失败" + ex.Message; } }
public void RenderGIF() { QREncoderMatrix matrix = QREncoderMatrix.Encode("www.sl.com/BMW-Z3", QRCorrectionLevel.H); using (System.IO.FileStream stream = new System.IO.FileStream("BMW-Z3.gif", System.IO.FileMode.Create)) { matrix.ToGIF(stream, scale: NFX.Media.TagCodes.QR.QRImageRenderer.ImageScale.Scale4x); stream.Flush(); } }
public void RenderBMP() { QREncoderMatrix matrix = QREncoderMatrix.Encode("ABCDEF", QRCorrectionLevel.H); using (System.IO.FileStream stream = new System.IO.FileStream("ABCDEF.bmp", System.IO.FileMode.Create)) { matrix.ToBMP(stream, scale: NFX.Media.TagCodes.QR.QRImageRenderer.ImageScale.Scale4x); stream.Flush(); } }
public override void Test() { OpenDMS.Storage.Providers.EngineRequest request = new OpenDMS.Storage.Providers.EngineRequest(); request.Engine = _engine; request.Database = _db; request.OnActionChanged += new EngineBase.ActionDelegate(EngineAction); request.OnProgress += new EngineBase.ProgressDelegate(Progress); request.OnComplete += new EngineBase.CompletionDelegate(Complete); request.OnTimeout += new EngineBase.TimeoutDelegate(Timeout); request.OnError += new EngineBase.ErrorDelegate(Error); request.AuthToken = _window.Session.AuthToken; request.RequestingPartyType = OpenDMS.Storage.Security.RequestingPartyType.User; Clear(); OpenDMS.Storage.Providers.CreateResourceArgs resourceArgs = new CreateResourceArgs() { VersionArgs = new CreateVersionArgs() }; resourceArgs.Metadata = new OpenDMS.Storage.Data.Metadata(); resourceArgs.Tags = new List<string>(); resourceArgs.Tags.Add("Tag1"); resourceArgs.Tags.Add("Tag2"); resourceArgs.Title = "Test resource"; resourceArgs.VersionArgs.Extension = "txt"; resourceArgs.VersionArgs.Metadata = new OpenDMS.Storage.Data.Metadata(); System.IO.FileStream fs = new System.IO.FileStream("testdoc.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, 8192, System.IO.FileOptions.None); byte[] bytes = System.Text.Encoding.ASCII.GetBytes("This is a test content file."); fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); fs.Dispose(); fs = new System.IO.FileStream("testdoc.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, 8192, System.IO.FileOptions.None); System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] data = md5.ComputeHash(fs); string output = ""; fs.Close(); md5.Dispose(); fs.Dispose(); for (int i = 0; i < data.Length; i++) output += data[i].ToString("x2"); resourceArgs.VersionArgs.Md5 = output; resourceArgs.VersionArgs.Content = new OpenDMS.Storage.Data.Content(bytes.Length, new OpenDMS.Storage.Data.ContentType("text/plain"), "testdoc.txt"); WriteLine("Starting CreateNewResource test..."); _start = DateTime.Now; _engine.CreateNewResource(request, resourceArgs); }
private const string Upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid"; // 上传扩展名 #endregion Fields #region Methods public JsonResult Upload() { var immediate = Request.QueryString["immediate"];//立即上传模式,仅为演示用 byte[] fileBytes; var disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"]; string localname; if (disposition != null) { fileBytes = Request.BinaryRead(Request.TotalBytes); localname = Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value;// 读取原始文件名 } else { var postedfile = Request.Files.Get(Inputname); if (postedfile == null || postedfile.ContentLength <= 0) return new NewtonsoftJsonResult() { Data = new { err = "无数据提交", msg = "无数据提交!" } }; fileBytes = new byte[postedfile.ContentLength]; postedfile.InputStream.Read(fileBytes, 0, postedfile.ContentLength); localname = postedfile.FileName; } var extension = GetFileExt(localname); //在小校验 if (fileBytes.Length > Maxattachsize) { var err = "文件大小不能超过" + ((double)Maxattachsize / (1024*1024)).ToString("#0.00") + "M"; return new NewtonsoftJsonResult() { Data = new { err, msg = err } }; } //扩展校验 if (("," + Upext + ",").IndexOf("," + extension + ",", System.StringComparison.CurrentCultureIgnoreCase) < 0) { var err = "上传文件扩展名必需为:" + Upext; return new NewtonsoftJsonResult() { Data = new { err, msg = err } }; } // 生成随机文件名 var random = new Random(DateTime.Now.Millisecond); var folder = CreateFolder(); var newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension; var fullPath = System.IO.Path.Combine(folder, newFileName); try { using (var fs = new System.IO.FileStream(Server.MapPath(fullPath), System.IO.FileMode.Create, System.IO.FileAccess.Write)) { fs.Write(fileBytes, 0, fileBytes.Length); fs.Flush(); } } catch (Exception e) { return new NewtonsoftJsonResult() { Data = new { err = e.Message, msg = e.Message } }; } return new NewtonsoftJsonResult { Data = new { err = "", msg = new { url = fullPath, localname, id = "1" } } }; }
public static void SaveFile() { try { System.IO.FileStream stream = new System.IO.FileStream("\\lastfiles.dat", System.IO.FileMode.Create); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize( stream, recentProjects ); formatter.Serialize( stream, recentFiles ); stream.Flush(); stream.Close(); } catch{} }
/// <summary> /// 保存上传的文件 /// </summary> /// <param name="postFileBase"></param> /// <param name="path"></param> /// <returns></returns> private File SaveHttpPostFile(HttpPostedFileBase postFileBase,string path) { System.IO.Stream uploadStream = null; System.IO.FileStream fs = null; File file = new File(); try { uploadStream = postFileBase.InputStream; int bufferLen = 1024; byte[] buffer = new byte[bufferLen]; int contentLen = 0; file.Name = System.IO.Path.GetFileName(postFileBase.FileName); file.ContentType = postFileBase.ContentType; file.RealPath = path + Guid.NewGuid().ToString(); fs = new System.IO.FileStream(file.RealPath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); while ((contentLen = uploadStream.Read(buffer, 0, bufferLen)) != 0) { fs.Write(buffer, 0, bufferLen); fs.Flush(); } } catch (Exception ex) { throw ex; } finally { if (null != fs) { fs.Close(); } if (null != uploadStream) { uploadStream.Close(); } } file.Size = GetFileSize(file.RealPath); file.Md5 = Md5Util.GetMD5HashFromFile(file.RealPath); return file; }
public static void Insert(UpgradePackage UpgradePackage) { try { // 存DB if ((int)FreightForwarder.Common.PackageSavingType.DB == UpgradePackage.SavingType) { (new PackageBusinesses()).AddUpgradePackage(UpgradePackage); } else { string folder = System.Web.HttpContext.Current.Server.MapPath("~/packages"); string filename = System.IO.Path.Combine(folder, UpgradePackage.FileName); System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(UpgradePackage.FileBytes, 0, UpgradePackage.FileBytes.Length); fs.Flush(); fs.Close(); string configfile = System.Web.HttpContext.Current.Server.MapPath("~/upgrade-packages.xml"); //XmlDocument doc = XMLHelper.xmlDoc(configfile); XmlDocument doc = new XmlDocument(); doc.Load(configfile); XmlNode pcnode = doc.SelectSingleNode("Packages/PackageCollection"); pcnode.AppendChild(UpgradePackage.ToXmlElement(doc)); doc.Save(configfile); //XmlNodeList partlistNode = assistXml.SelectNodes("Assist/PartCollection/Part"); //foreach (XmlNode node in partlistNode) //{ // Part part = new Part(); // part.FromXmlNode(node); // Parts.Add(part); //} } } catch (Exception ex) { throw ex; } }
private static void WriteBytes(System.IO.FileInfo aFile, long size) { System.IO.Stream stream = null; try { stream = new System.IO.FileStream(aFile.FullName, System.IO.FileMode.Create); for (int i = 0; i < size; i++) { stream.WriteByte((byte) Byten(i)); } stream.Flush(); } finally { if (stream != null) { stream.Close(); } } }
private void CopyDatabase(string dataBaseName) { var dbPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dataBaseName); if (!System.IO.File.Exists(dbPath)) { var dbAssetStream = Assets.Open(dataBaseName); var dbFileStream = new System.IO.FileStream(dbPath, System.IO.FileMode.OpenOrCreate); var buffer = new byte[1024]; int b = buffer.Length; int length; while ((length = dbAssetStream.Read(buffer, 0, b)) > 0) { dbFileStream.Write(buffer, 0, length); } dbFileStream.Flush(); dbFileStream.Close(); dbAssetStream.Close(); } }
private void 保存记录ToolStripMenuItem_Click(object sender, EventArgs e) { ListView lv = listView1; string s = string.Empty; for (int i = 0; i < lv.Columns.Count; i++) { s += lv.Columns[i].Text + ","; } s += "\n"; for (int i = 0; i < lv.Items.Count; i++) { //s += (lv.Items[i].Text + ","); for (int j = 0; j < lv.Items[i].SubItems.Count; j++) { s += lv.Items[i].SubItems[j].Text + ","; } s += "\n"; } //MessageBox.Show(s); SaveFileDialog sf = new SaveFileDialog(); sf.Filter = "CSV文件|*.csv"; sf.AddExtension = true; sf.Title = "保存到文件:"; sf.FileName = string.Format("CAN{0}数据文件{1}", CANChannel.Channel, DateTime.Now.ToString("yyyy-M-d-H-m-s").Replace(' ', '-')); if (sf.ShowDialog() == DialogResult.OK) { System.IO.FileStream fs = new System.IO.FileStream(sf.FileName, System.IO.FileMode.Create); byte[] data = Encoding.Default.GetBytes(s); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } }
public override void Sync(System.String name) { EnsureOpen(); System.IO.FileInfo fullFile = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)); bool success = false; int retryCount = 0; System.IO.IOException exc = null; while (!success && retryCount < 5) { retryCount++; System.IO.FileStream file = null; try { try { file = new System.IO.FileStream(fullFile.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); //TODO // {{dougsale-2.4}}: // // in Lucene (Java): // file.getFD().sync(); // file is a java.io.RandomAccessFile // getFD() returns java.io.FileDescriptor // sync() documentation states: "Force all system buffers to synchronize with the underlying device." // // what they try to do here is get ahold of the underlying file descriptor // for the given file name and make sure all (downstream) associated system buffers are // flushed to disk // // how do i do that in .Net? flushing the created stream might inadvertently do it, or it // may do nothing at all. I can find references to the file HANDLE, but it's not really // a type, simply an int pointer. // // where is FSDirectory.Sync(string name) called from - if this isn't a new feature but rather a refactor, maybe // i can snip the old code from where it was re-factored... file.Flush(); success = true; } finally { if (file != null) file.Close(); } } catch (System.IO.IOException ioe) { if (exc == null) exc = ioe; try { // Pause 5 msec System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 5)); } catch (System.Threading.ThreadInterruptedException ie) { // In 3.0 we will change this to throw // InterruptedException instead SupportClass.ThreadClass.Current().Interrupt(); throw new System.SystemException(ie.ToString(), ie); } } } if (!success) // Throw original exception throw exc; }
public bool save(string _filename = null) { if (_filename == null) _filename = filename; XmlSerializer serializer = new XmlSerializer(typeof(List<User>)); System.IO.FileStream fstream = new System.IO.FileStream(_filename, System.IO.FileMode.OpenOrCreate); serializer.Serialize(fstream, Users); fstream.Flush(); fstream.Close(); return true; }
private void SerialRead() { // The code continuously looks for sync bytes, after which a valid measurement is // added to the data buffer ++triggerCount; byte[] readBuffer = new byte[packetSize]; short[] convertBuffer = new short[1]; byte[] tagByte = new byte[1]; byte[] timeByte = new byte[2]; byte[] valueByte = new byte[2]; System.IO.FileStream logWriter = new System.IO.FileStream(@"C:\VR_SYSTEM\Data\sensor.bin", System.IO.FileMode.Create, System.IO.FileAccess.Write); while (isRecording) { if (sendTag) { serial_port.Write(writeBuffer, 0, 1); sendTag = false; } if (serial_port.ReadByte() == 0xff) { if (serial_port.ReadByte() == 0xff) { serial_port.Read(readBuffer,0,packetSize); Buffer.BlockCopy(readBuffer, 0, tagByte, 0, 1); Buffer.BlockCopy(readBuffer, 1, timeByte, 0, 2); Buffer.BlockCopy(readBuffer, 3, valueByte, 0, 2); Buffer.BlockCopy(valueByte, 0, convertBuffer, 0, 2); Buffer.BlockCopy(dataBuffer, 2, dataBuffer, 0, sizeof(short) * bufferSize - 2); dataBuffer[bufferSize-1] = convertBuffer[0]; bufferCount += 1; byteCount += packetSize +2; logWriter.Write(readBuffer, 0, packetSize); } } } logWriter.Flush(); logWriter.Close(); }
/// <summary> /// Iterate a collection of service descriptions and generate Wsdl's /// </summary> /// <param name="serviceDescriptions">A ServiceDescriptionCollection containing the colleciton of service descriptions.</param> /// <param filename="serviceDescriptions">A string containing the name of th wsdl file. If null the name of the service description is used.</param> /// <param name="destinationPath">A string containing the name of a directory where the wsdl file is created.</param> public void GenerateWsdls(ServiceDescriptionCollection serviceDescriptions, string filename, string destinationPath) { // Fix namespaces to Dpws spec string dpwsNs = "http://schemas.xmlsoap.org/ws/2006/02/devprof"; string policyNs = "http://schemas.xmlsoap.org/ws/2004/09/policy"; XmlSerializerNamespaces serviceNamespaces = new XmlSerializerNamespaces(); serviceNamespaces.Add("wsa", "http://schemas.xmlsoap.org/ws/2004/08/addressing"); serviceNamespaces.Add("wsdl", "http://schemas.xmlsoap.org/wsdl/"); serviceNamespaces.Add("wsdp", dpwsNs); serviceNamespaces.Add("wse", "http://schemas.xmlsoap.org/ws/2004/08/eventing"); serviceNamespaces.Add("wsoap12", "http://schemas.xmlsoap.org/wsdl/soap12/"); serviceNamespaces.Add("wsp", policyNs); serviceNamespaces.Add("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); // For each service description in the service description collection generate a wsdl bool newFile = true; foreach (ServiceDescription serviceDesc in serviceDescriptions) { // Fix the namespaces serviceNamespaces.Add("tns", serviceDesc.TargetNamespace); serviceDesc.Namespaces = serviceNamespaces; XmlSchemaSet schemaSet = new XmlSchemaSet(); foreach (XmlSchema schema in serviceDesc.Types.Schemas) schemaSet.Add(schema); schemaSet.Compile(); if (filename == null) { Logger.WriteLine("Writing Wsdl File: " + destinationPath + serviceDesc.Name + ".wsdl", LogLevel.Normal); // Write the content System.IO.FileStream fileStream = null; fileStream = new System.IO.FileStream(destinationPath + serviceDesc.Name + ".wsdl", System.IO.FileMode.Create); serviceDesc.Write(fileStream); fileStream.Flush(); fileStream.Close(); } else { System.IO.FileStream fileStream = null; if (serviceDescriptions.Count > 1 && !newFile) { Logger.WriteLine("Appending " + serviceDesc.Name + " Service Description to: " + destinationPath + filename, LogLevel.Normal); fileStream = new System.IO.FileStream(destinationPath + filename, System.IO.FileMode.Append); } else { Logger.WriteLine("Writing " + serviceDesc.Name + " Service Description to: " + destinationPath + filename, LogLevel.Normal); fileStream = new System.IO.FileStream(destinationPath + filename, System.IO.FileMode.Create); newFile = false; } // Write the content serviceDesc.Write(fileStream); fileStream.Flush(); fileStream.Write(new byte[] { 0x0D, 0x0A, 0x0D, 0x0A }, 0, 4); fileStream.Flush(); fileStream.Close(); } } }
private void ExtractConfig( ) { this.LogDebug ( "Extracting configuration file" ); if ( this.InvokeRequired ) { this.Invoke ( new SetControlTextDelegate ( SetControlText ), status, "Extracting Configuration File" ); } else { SetControlText ( status, "Extracting Configuration File" ); } System.IO.FileInfo config = new System.IO.FileInfo ( System.IO.Path.Combine ( CommandRunner.Instance.TempDataPath, "BareBonesBackup.config" ) ); using ( System.IO.FileStream fs = new System.IO.FileStream ( config.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write ) ) { byte[] bytes = Encoding.Default.GetBytes ( Properties.Resources.BareBonesBackup_config ); fs.Write ( bytes, 0, bytes.Length ); fs.Flush ( ); } }
protected override void EndFilelist() { try { #region End Xml document writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); #endregion Utils.FileOperations.PathExists(systemPath); baseStream = new System.IO.FileStream(systemPath + FileName, System.IO.FileMode.Create); xmlBaseStream.Position = 0; // We dont want to have filelist compressed by bz2. #region Write xml content to file. if (!bz2) { byte[] buffer = new byte[2048]; size = 0; int pos; while ((pos = xmlBaseStream.Read(buffer, 0, buffer.Length)) != 0) { baseStream.Write(buffer, 0, pos); size += pos; } writer.Close(); baseStream.Flush(); baseStream.Close(); return; } #endregion #region Bz2 size = Utils.Compression.Bz2.Compress(xmlBaseStream, baseStream, 512); writer.Close(); #endregion // If no error has occured. Show that it has finished without errors. hasWritenFilelist = true; } catch (System.UnauthorizedAccessException) { } catch (System.Security.SecurityException) { } catch (System.ArgumentException) { } catch (System.IO.IOException) { } // TODO : Add Events for showing errors here. }
/// <summary> /// 下载文件 /// </summary> public void FileDow(string DBFullName, string FullName) { string FileName = System.IO.Path.GetFileName(FullName); string CFolder = System.IO.Path.GetDirectoryName(FullName); string DBFolder = System.IO.Path.GetDirectoryName(DBFullName); // 准备本地目录 if (!System.IO.Directory.Exists(CFolder)) { System.IO.Directory.CreateDirectory(CFolder); } // 1.写入数据库 Apq.Data.Common.DbConnectionHelper.Open(Connection); System.Data.Common.DbCommand sqlCmd = Connection.CreateCommand(); sqlCmd.CommandText = "Apq_FileTrans_Insert_ADO"; sqlCmd.CommandType = CommandType.StoredProcedure; Apq.Data.Common.DbCommandHelper cmdHelper = new Apq.Data.Common.DbCommandHelper(sqlCmd); cmdHelper.AddParameter("@FullName", DBFullName); cmdHelper.AddParameter("@CFolder", CFolder); cmdHelper.AddParameter("@ID", 0); sqlCmd.Parameters["@ID"].Direction = ParameterDirection.InputOutput; sqlCmd.ExecuteNonQuery(); int ID = Apq.Convert.ChangeType<int>(sqlCmd.Parameters["@ID"].Value); // 2.读取到本地 DataSet ds = new DataSet(); Apq.Data.Common.DbConnectionHelper connHelper = new Apq.Data.Common.DbConnectionHelper(Connection); DbDataAdapter da = connHelper.CreateAdapter(); da.SelectCommand.CommandText = "Apq_FileTrans_List"; da.SelectCommand.CommandType = CommandType.StoredProcedure; Apq.Data.Common.DbCommandHelper daHelper = new Apq.Data.Common.DbCommandHelper(da.SelectCommand); daHelper.AddParameter("@ID", ID); da.Fill(ds); // 3.保存文件 if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { byte[] bFile = Apq.Convert.ChangeType<byte[]>(ds.Tables[0].Rows[0]["FileStream"]); System.IO.FileStream fs = new System.IO.FileStream(FullName, System.IO.FileMode.Create); fs.Write(bFile, 0, bFile.Length); fs.Flush(); fs.Close(); } // 4.删除数据库行 da.SelectCommand.CommandText = "Apq_FileTrans_Delete"; da.SelectCommand.ExecuteNonQuery(); }
//================== Сортировки ==================== /// <summary> /// Слияние двух участков одной ячейки первого (он в младшей индексной части) и второго, следующего за ним. /// Результирующий массив начинается с начала первого участка. Слияние производится сравнением объектных значений /// элементов посредством функции сравнения ComparePO /// </summary> /// <param name="tel">Тип элемента последовательности</param> /// <param name="off1">offset начала первого участка</param> /// <param name="number1">длина первого участка</param> /// <param name="off2">offset начала второго участка</param> /// <param name="number2">длина второго участка</param> /// <param name="comparePO">Функция сравнения объектных представлений элементов</param> internal void CombineParts(PType tel, long off1, long number1, long off2, long number2, Func<object, object, int> comparePO) { long pointer_out = off1; long pointer_in = off2; int size = tel.HeadSize; // Используем временный файл string tmp_fname = null; //MachineInfo.pathForTmp + "tmp_merge.pac"; int last_slash = _filePath.LastIndexOfAny(new char[] { '/', '\\' }); if (last_slash == -1) tmp_fname = "C:/tmp/tmp_merge.pac"; else tmp_fname = _filePath.Substring(0, last_slash + 1) + "tmp_merge.pac"; System.IO.FileStream tmp_fs = new System.IO.FileStream(tmp_fname, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); System.IO.BinaryReader tmp_br = new System.IO.BinaryReader(tmp_fs); // Перепишем number1 * size байтов от начальной точки во временный файл (Первую часть) this.SetOffset(pointer_out); long bytestocopy = number1 * size; int buffLen = 8192; byte[] buff = new byte[buffLen * size]; while (bytestocopy > 0) { int nb = bytestocopy < buff.Length ? (int)bytestocopy : buff.Length; this.fs.Read(buff, 0, nb); tmp_fs.Write(buff, 0, nb); bytestocopy -= nb; } tmp_fs.Flush(); // теперь будем сливать массивы long cnt1 = 0; // число переписанных элементов первой подпоследовательности long cnt2 = 0; // число переписанных элементов второй подпоследовательности tmp_fs.Position = 0L; // Установка начальной позиции в файле this.SetOffset(pointer_in); // Установка на начало второй части последовательности в ячейке System.IO.Stream fs1 = tmp_fs; // Первый поток System.IO.Stream fs2 = this.fs; // Второй поток // Микробуфера для элементов byte[] m_buf1 = new byte[size]; byte[] m_buf2 = new byte[size]; // Заполнение микробуферов fs1.Read(m_buf1, 0, size); fs2.Read(m_buf2, 0, size); pointer_in += size; // Это чтобы читать P-значения System.IO.BinaryReader m_reader1 = new System.IO.BinaryReader(new System.IO.MemoryStream(m_buf1)); System.IO.BinaryReader m_reader2 = new System.IO.BinaryReader(new System.IO.MemoryStream(m_buf2)); // Текущие объекты object val1 = PaCell.GetPO(tel, m_reader1); object val2 = PaCell.GetPO(tel, m_reader2); // Писать будем в тот же буффер buff, текущее место записи: int ind_buff = 0; // Слияние!!! while (cnt1 < number1 && cnt2 < number2) { if (comparePO(val1, val2) < 0) { // Продвигаем первую подпоследовательность Buffer.BlockCopy(m_buf1, 0, buff, ind_buff, size); cnt1++; if (cnt1 < number1) // Возможен конец { fs1.Read(m_buf1, 0, size); m_reader1.BaseStream.Position = 0; val1 = PaCell.GetPO(tel, m_reader1); } } else { // Продвигаем вторую последовательность Buffer.BlockCopy(m_buf2, 0, buff, ind_buff, size); cnt2++; if (cnt2 < number2) // Возможен конец { this.SetOffset(pointer_in); // Установка на текущее место чтения !!!!!!!!! fs2.Read(m_buf2, 0, size); pointer_in += size; m_reader2.BaseStream.Position = 0; val2 = PaCell.GetPO(tel, m_reader2); } } ind_buff += size; // Если буфер заполнился, его надо сбросить if (ind_buff == buff.Length) { this.SetOffset(pointer_out); int volume = ind_buff; this.fs.Write(buff, 0, volume); pointer_out += volume; ind_buff = 0; } } // Если в буфере остались данные, их надо сбросить if (ind_buff > 0) { this.SetOffset(pointer_out); int volume = ind_buff; this.fs.Write(buff, 0, volume); pointer_out += volume; } // Теперь надо переписать остатки if (cnt1 < number1) { this.SetOffset(pointer_out); // Здесь запись ведется подряд, без перемещений головки чтения/записи // Сначала запишем уже прочитанную запись this.fs.Write(m_buf1, 0, size); // а теперь - остальное bytestocopy = (number1 - cnt1 - 1) * size; while (bytestocopy > 0) { int nbytes = buff.Length; if (bytestocopy < nbytes) nbytes = (int)bytestocopy; fs1.Read(buff, 0, nbytes); this.fs.Write(buff, 0, nbytes); bytestocopy -= nbytes; } } else if (cnt2 < number2) { // Поскольку в тот же массив, то надо переписать только прочитанный, а остатки массива уже на своем месте //this.cell.SetOffset(pointer_out); //this.cell.fs.Write(m_buf2, 0, size); } this.fs.Flush(); // Закрываем временный файл tmp_fs.Flush(); //.Close(); // Убираем временный файл //File.Delete(tmp_fname); // не убираем, а то он помещается в мусорную корзину, а так - будет переиспользоваться }
public static void SaveAssembly2(string assemblyName, string destinationPath) { string sql = @"SELECT af.name, af.content FROM sys.assemblies a INNER JOIN sys.assembly_files af ON a.assembly_id = af.assembly_id WHERE a.name = @assemblyname"; using (System.Data.Common.DbConnection conn = new System.Data.SqlClient.SqlConnection("context connection=true")) //Create current context connection { using (System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand(sql, (System.Data.SqlClient.SqlConnection)conn)) { System.Data.Common.DbParameter param = new System.Data.SqlClient.SqlParameter("@assemblyname", System.Data.SqlDbType.NVarChar); param.Value = assemblyName; // param.Size = 128; cmd.Parameters.Add(param); using (System.IO.Stream fs = new System.IO.FileStream("logo" + "pub_id" + ".bmp", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { long startIndex = 0; var buffer = new byte[1024]; int bufferSize = buffer.Length; if(cmd.Connection.State != System.Data.ConnectionState.Open) cmd.Connection.Open(); //Open the context connetion using (System.Data.Common.DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) //Iterate through assembly files { string assemblyFileName = reader.GetString(0); //get assembly file name from the name (first) column long retval = reader.GetBytes(1, startIndex, buffer, 0, bufferSize); // Continue reading and writing while there are bytes beyond the size of the buffer. while (retval == bufferSize) { bw.Write(buffer); bw.Flush(); // Reposition the start index to the end of the last buffer and fill the buffer. startIndex += bufferSize; retval = reader.GetBytes(1, startIndex, buffer, 0, bufferSize); } // Whend // Write the remaining buffer. bw.Write(buffer, 0, (int)retval); bw.Flush(); bw.Close(); } // Whend reader.Read } // End Using reader } // End using bw fs.Flush(); fs.Close(); } // End using fs } // End using cmd if (conn.State != System.Data.ConnectionState.Closed) conn.Close(); } // End Using conn }
private void btnSaveStream_Click(object sender, RoutedEventArgs e) { SaveFileDialog savefile = new SaveFileDialog() { Filter = "Pdf Document(*.Pdf)|*.Pdf", Title = "Save" }; bool? result = savefile.ShowDialog(); if (result.Value) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); //Pdf document to save the file stream. pdfViewer1.SaveToFile(stream); stream.Position = 0; byte[] fileBytes = stream.ToArray(); stream.Close(); System.IO.FileStream fileStream = new System.IO.FileStream(savefile.FileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); fileStream.Write(fileBytes, 0, fileBytes.Length); fileStream.Flush(); fileStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
private void copyAssets() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String mSoundFontDir = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString() + "/"; string mSoundFontDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).ToString() + "/"; string[] files = null; string mkdir = null; AssetManager assetManager = Assets; try { files = assetManager.list(""); } catch (IOException e) { Log.e(TAG, e.Message); Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); return; } for (int i = 0; i < files.Length; i++) { System.IO.Stream @in = null; System.IO.Stream @out = null; try { File tmp = new File(mSoundFontDir, files[i]); if (!tmp.exists()) { @in = assetManager.open(files[i]); } if (@in == null) { continue; } mkdir = mSoundFontDir; File mpath = new File(mkdir); if (!mpath.Directory) { mpath.mkdirs(); } @out = new System.IO.FileStream(mSoundFontDir + files[i], System.IO.FileMode.Create, System.IO.FileAccess.Write); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final byte[] buffer = new byte[1024]; sbyte[] buffer = new sbyte[1024]; int read; while ((read = @in.Read(buffer, 0, buffer.Length)) != -1) { @out.Write(buffer, 0, read); } @in.Close(); @in = null; @out.Flush(); @out.Close(); @out = null; } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } } }
// private void getFile(byte[] content, string filePath) { string fileName = filePath; if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } //FileStream sw = new FileStream(@fileName, FileMode.Create); //StreamWriter fs = new StreamWriter(sw, Encoding.UTF8); //fs.Write(entity.Content); System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create); fs.Write(content, 0, content.Length); fs.Flush(); fs.Close(); fileName = System.IO.Path.Combine(Application.StartupPath, fileName); }
private void WriteModifications(string dataHistoryFile, IIntegrationResult result) { System.IO.FileStream fs = new System.IO.FileStream( dataHistoryFile, System.IO.FileMode.Append); fs.Seek(0, System.IO.SeekOrigin.End); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); System.Xml.XmlTextWriter currentBuildInfoWriter = new System.Xml.XmlTextWriter(sw); currentBuildInfoWriter.Formatting = System.Xml.Formatting.Indented; currentBuildInfoWriter.WriteStartElement("Build"); WriteXMLAttributeAndValue(currentBuildInfoWriter, "BuildDate", Util.DateUtil.FormatDate(result.EndTime)); WriteXMLAttributeAndValue(currentBuildInfoWriter, "Success", result.Succeeded.ToString(CultureInfo.CurrentCulture)); WriteXMLAttributeAndValue(currentBuildInfoWriter, "Label", result.Label); if (result.Modifications.Length > 0) { currentBuildInfoWriter.WriteStartElement("modifications"); for (int i = 0; i < result.Modifications.Length; i++) { result.Modifications[i].ToXml(currentBuildInfoWriter); } currentBuildInfoWriter.WriteEndElement(); } currentBuildInfoWriter.WriteEndElement(); sw.WriteLine(); sw.Flush(); fs.Flush(); sw.Close(); fs.Close(); }
/// <summary> /// Saves recently opened documents list to the file specified. /// </summary> /// <param name="fileName"> /// Path of the file to save lists to. /// </param> public static void SaveListToFile(string fileName) { try { System.IO.Stream stream = new System.IO.FileStream(fileName,System.IO.FileMode.Create); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize( stream, recentProjectsList ); formatter.Serialize( stream, recentFilesList ); stream.Flush(); stream.Close(); } catch{} }
static void Main(string[] args) { #region Constantes const string archivo = @"c:\streams.txt"; const string cadena = "Ejemplo de guardar datos utilizando clases basadas en stream"; #endregion #region Guardar archivo Console.WriteLine("Guardando datos"); // Abrimos o creamos el fichero, para escribir en él System.IO.FileStream fsWrite = new System.IO.FileStream(archivo, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); // Escribimos algunas cadenas, // el problema es que solo podemos escribir arrays de bytes, // por tanto debemos convertir la cadena en un array de bytes byte[] datosWrite; // pero usando la codificación que creamos conveniente // de forma predeterminada es UTF-8 System.Text.UTF8Encoding encWrite = new System.Text.UTF8Encoding(); // convertimos la cadena en un array de bytes datosWrite = encWrite.GetBytes(cadena); // lo escribimos en el stream fsWrite.Write(datosWrite, 0, datosWrite.Length); // nos aseguramos que se escriben todos los datos fsWrite.Flush(); // cerramos el stream fsWrite.Close(); #endregion #region Leer archivo Console.WriteLine("Leyendo datos"); // Los bloques leídos los almacenaremos en un StringBuilder System.Text.StringBuilder res = new System.Text.StringBuilder(); // Abrimos el fichero para leer de él System.IO.FileStream fs = new System.IO.FileStream(archivo, System.IO.FileMode.Open, System.IO.FileAccess.Read); // los datos se leerán en bloques de 1024 bytes (1 KB) byte[] datos = new byte[1025]; System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); // Para usar la codificación de Windows //System.Text.Encoding enc = System.Text.Encoding.Default; // leemos mientras hay algo en el fichero while (fs.Read(datos, 0, 1024) > 0) { // agregamos al stringBuilder los bytes leídos // (convertidos en una cadena) res.Append(enc.GetString(datos)); } // cerramos el buffer fs.Close(); // devolvemos todo lo leído Console.WriteLine(res.ToString()); Console.ReadLine(); #endregion }
static int Main(string[] args) { if (args.Length != 3) Console.WriteLine("usage: fileSplitter <file> <blocksize> <outDir>"); System.IO.FileStream fs = null; int blockSize = 0; string outDir = null; try { fs = new System.IO.FileStream(args[0], System.IO.FileMode.Open); if (args[1].StartsWith("0x")) blockSize = Convert.ToInt32(args[1], 16); else blockSize = Convert.ToInt32(args[1], 10); if (!System.IO.Directory.Exists(args[2])) outDir = System.IO.Directory.CreateDirectory(args[2]).FullName + '\\'; else outDir = new System.IO.DirectoryInfo(args[2]).FullName + "\\"; } catch (Exception e) { Console.WriteLine(e.Message); return 1; } Console.WriteLine("Splitting {0} to {1} into {2} bytes blocks.", fs.Name, outDir, blockSize); long remaining = fs.Length; int packetNbr = 0; System.IO.StreamWriter hashFile = new System.IO.StreamWriter(outDir + "hash.txt"); int qzdqzdqd = 0; while (remaining > 0) { // Write packet file System.IO.FileStream packetFile = new System.IO.FileStream(outDir + packetNbr.ToString(), System.IO.FileMode.Create); byte[] buffer = new byte[blockSize]; int BytesRead = fs.Read(buffer, 0, blockSize); Console.WriteLine("Writting {0} to {1}.", BytesRead, packetFile.Name); packetFile.Write(buffer, 0, BytesRead); packetFile.Flush(); // Calculate sha1 hash System.Security.Cryptography.SHA1 sha1CSP = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] hash = sha1CSP.ComputeHash(buffer, 0, BytesRead); string sHash = BitConverter.ToString(hash); sHash = sHash.Replace("-", ""); qzdqzdqd += sHash.Length; // write hash hashFile.Write(sHash); remaining -= BytesRead; packetNbr++; } hashFile.Flush(); return 0; }
private void ProcessSpawn(MapClient client, string args) { string[] arg = args.Split(' '); if (arg.Length < 3) { client.SendMessage(_MasterName, "Invalid parameters!", SagaMap.Packets.Server.SendChat.MESSAGE_TYPE.SYSTEM_MESSAGE); return; } System.IO.FileStream fs = new System.IO.FileStream("autospawn.xml", System.IO.FileMode.Append); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); sw.WriteLine(" <spawn>"); sw.WriteLine(string.Format(" <id>{0}</id>", arg[0])); sw.WriteLine(string.Format(" <map>{0}</map>", MapManager.Instance.GetMapName(client.Char.mapID))); sw.WriteLine(string.Format(" <x>{0}</x>", (int)client.Char.x)); sw.WriteLine(string.Format(" <y>{0}</y>", (int)client.Char.y)); if (arg.Length == 4) sw.WriteLine(string.Format(" <z>{0}</z>", (int)client.Char.z)); sw.WriteLine(string.Format(" <amount>{0}</amount>", arg[1])); sw.WriteLine(string.Format(" <range>{0}</range>", arg[2])); sw.WriteLine(" </spawn>"); sw.Flush(); fs.Flush(); fs.Close(); client.SendMessage(_MasterName, string.Format("Spawn:{0} amount:{1} range:{2} added", arg[0], arg[1], arg[2]), SagaMap.Packets.Server.SendChat.MESSAGE_TYPE.SYSTEM_MESSAGE); }
public void Page_Load() { Response.Charset = "UTF-8"; // 初始化一大堆变量 string inputname = "filedata";//表单文件域name string attachdir = "UPLOAD"; // 上传文件保存路径,结尾不要带/ int dirtype = 1; // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存 int maxattachsize = 2097152; // 最大上传大小,默认是2M string upext = "gif,jpg,jpeg,png,bmp,txt,rar,zip,ppt,pptx,doc,docx,xls,xlsx,swf,flv,pdf"; // 上传扩展名 int msgtype = 2; //返回上传参数的格式:1,只返回url,2,返回参数数组 string immediate = Request.QueryString["immediate"];//立即上传模式,仅为演示用 byte[] file; // 统一转换为byte数组处理 string localname = ""; string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"]; string err = ""; string msg = "''"; if (disposition != null) { // HTML5上传 file = Request.BinaryRead(Request.TotalBytes); localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名 } else { HttpFileCollectionBase filecollection = Request.Files; HttpPostedFileBase postedfile = filecollection.Get(inputname); // 读取原始文件名 localname = postedfile.FileName; // 初始化byte长度. file = new Byte[postedfile.ContentLength]; // 转换为byte类型 System.IO.Stream stream = postedfile.InputStream; stream.Read(file, 0, postedfile.ContentLength); stream.Close(); filecollection = null; } if (file.Length == 0) err = "无数据提交"; else { if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节"; else { string attach_dir, attach_subdir, filename, extension, target; // 取上载文件后缀名 extension = GetFileExt(localname); if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传文件扩展名必需为:" + upext; else { switch (dirtype) { case 2: attach_subdir = "month_" + DateTime.Now.ToString("yyMM"); break; case 3: attach_subdir = "ext_" + extension; break; default: attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd"); break; } attach_dir = "/" + attachdir + "/" + attach_subdir + "/"; // 生成随机文件名 Random random = new Random(DateTime.Now.Millisecond); filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension; target = attach_dir + filename; try { CreateFolder(Server.MapPath(attach_dir)); System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(file, 0, file.Length); fs.Flush(); fs.Close(); } catch (Exception ex) { err = ex.Message.ToString(); } // 立即模式判断 if (immediate == "1") target = "!" + target; target = jsonString(target); if (msgtype == 1) msg = "'" + target + "'"; else msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}"; } } } file = null; Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}"); }
public bool load(string _filename = null) { if (_filename == null) _filename = filename; if (!System.IO.File.Exists(_filename)) return false; XmlSerializer serializer = new XmlSerializer(typeof(List<User>)); System.IO.FileStream fstream = new System.IO.FileStream(_filename, System.IO.FileMode.Open); Users = (List<User>)serializer.Deserialize(fstream); foreach (User usr in Users) { if (!string.IsNullOrWhiteSpace(usr.AccessToken)) usr.Initialize(); } fstream.Flush(); fstream.Close(); return true; }