public void CreateFromDirectory( string Dir, string Outfile ) { string[] Filepaths = System.IO.Directory.GetFiles( Dir ); ushort Filecount = (ushort)Filepaths.Length; uint RequiredBytesForHeader = Util.Align( Filecount * 3u + 5u, 0x10u ); // 3 bytes per filesize + 3 bytes for an extra pointer to first file + 2 bytes for filecount var Filestream = new System.IO.FileStream( Outfile, System.IO.FileMode.Create ); // header Filestream.Write( BitConverter.GetBytes( Filecount ), 0, 2 ); Filestream.Write( Util.GetBytesForUInt24( RequiredBytesForHeader ), 0, 3 ); uint TotalFilesize = RequiredBytesForHeader; foreach ( string Path in Filepaths ) { TotalFilesize += (uint)( new System.IO.FileInfo( Path ).Length ); Filestream.Write( Util.GetBytesForUInt24( TotalFilesize ), 0, 3 ); TotalFilesize = TotalFilesize.Align( 0x10u ); } while ( Filestream.Length < RequiredBytesForHeader ) { Filestream.WriteByte( 0x00 ); } // files foreach ( string Path in Filepaths ) { var File = new System.IO.FileStream( Path, System.IO.FileMode.Open ); Util.CopyStream( File, Filestream, (int)File.Length ); File.Close(); while ( Filestream.Length % 0x10 != 0 ) { Filestream.WriteByte( 0x00 ); } } Filestream.Close(); }
static void Main(string[] args) { Console.Write("> Введите количество файлов: "); int n = 0; Int32.TryParse(Console.ReadLine(), out n); int[] setOfItems = new int[n]; Random rnd = new Random(); Dictionary<int, bool> tmpHash = new Dictionary<int, bool>(); for (int i = 0; i < n * 2; ++i) { tmpHash[i] = false; } // Get a set of numbers int j = 0; while(j < n) { int randomNumber = rnd.Next(0, n * 2); if (!tmpHash[randomNumber]) { Console.WriteLine(randomNumber.ToString()); setOfItems[j++] = randomNumber; tmpHash[randomNumber] = true; } } Console.WriteLine("... набор данных готов!"); // Saving to the file Console.Write("> Введите имя файла: "); String filename = "w:\\Zd02\\"; filename += Console.ReadLine(); int count = n; byte[] buffer = new byte[4]; try { using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { buffer = BitConverter.GetBytes(count); fs.Write(buffer, 0, buffer.Length); for (int i = 0; i < count; ++i) { buffer = BitConverter.GetBytes(setOfItems[i]); fs.Write(buffer, 0, buffer.Length); } fs.Close(); } Console.WriteLine(String.Format("... файл сохранен как {0}!", filename)); } catch (System.Exception ex) { Console.WriteLine("... Error! " + ex.ToString()); } Console.ReadLine(); }
static void Main(string[] args) { try { // open file to output extracted fragments System.IO.FileInfo f1 = new System.IO.FileInfo("./out.txt"); System.IO.FileStream fos = new System.IO.FileStream(f1.FullName, System.IO.FileMode.Create); // instantiate the parser VTDGen vg = new VTDGen(); if (vg.parseFile("./soap2.xml", true)) { VTDNav vn = vg.getNav(); // get to the SOAP header if (vn.toElementNS(VTDNav.FC, "http://www.w3.org/2003/05/soap-envelope", "Header")) { if (vn.toElement(VTDNav.FC)) // to first child { do { // test MUSTHAVE if (vn.hasAttrNS("http://www.w3.org/2003/05/soap-envelope", "mustUnderstand")) { long l = vn.getElementFragment(); int len = (int)(l >> 32); int offset = (int)l; byte[] b = vn.getXML().getBytes(); fos.Write(b, offset, len); //write the fragment out into out.txt System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("ASCII"); byte[] bytes = encoder.GetBytes("\n=========\n"); fos.Write(bytes, 0, bytes.Length); } } while (vn.toElement(VTDNav.NS)); // navigate next sibling } else System.Console.Out.WriteLine("Header has not child elements"); } else System.Console.Out.WriteLine(" Dosesn't have a header"); fos.Close(); } } catch (NavException e) { System.Console.Out.WriteLine(" Exception during navigation " + e); } catch (System.IO.IOException e) { System.Console.Out.WriteLine(" IO exception condition" + e); } }
public static void SaveAssembly(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 (SqlConnection conn = new SqlConnection("context connection=true")) //Create current context connection { using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlParameter param = new SqlParameter("@assemblyname", System.Data.SqlDbType.NVarChar); param.Value = assemblyName; // param.Size = 128; cmd.Parameters.Add(param); cmd.Connection.Open(); //Open the context connetion using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) //Iterate through assembly files { string assemblyFileName = reader.GetString(0); //get assembly file name from the name (first) column System.Data.SqlTypes.SqlBytes bytes = reader.GetSqlBytes(1); //get assembly binary data from the content (second) column string outputFile = System.IO.Path.Combine(destinationPath, assemblyFileName); SqlContext.Pipe.Send(string.Format("Exporting assembly file [{0}] to [{1}]", assemblyFileName, outputFile)); //Send information about exported file back to the calling session using (System.IO.FileStream byteStream = new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew)) { byteStream.Write(bytes.Value, 0, (int)bytes.Length); byteStream.Close(); } } } } conn.Close(); } }
public void LogError(Exception ex, string source) { try { String LogFile = HttpContext.Current.Request.MapPath("/Errorlog.txt"); if (LogFile != "") { String Message = String.Format("{0}{0}=== {1} ==={0}{2}{0}{3}{0}{4}{0}{5}" , Environment.NewLine , DateTime.Now , ex.Message , source , ex.InnerException , ex.StackTrace); byte[] binLogString = Encoding.Default.GetBytes(Message); System.IO.FileStream loFile = new System.IO.FileStream(LogFile , System.IO.FileMode.OpenOrCreate , System.IO.FileAccess.Write, System.IO.FileShare.Write); loFile.Seek(0, System.IO.SeekOrigin.End); loFile.Write(binLogString, 0, binLogString.Length); loFile.Close(); } } catch { /*No need to catch the error here. */} }
private void button1_Click(object sender, EventArgs e) { if (listBox1.SelectedItem!=null) { SaveFileDialog sav=new SaveFileDialog(); sav.Filter = "*.hex|*.hex|*.*|*'.*"; DialogResult res = sav.ShowDialog(); if (res==DialogResult.OK) { try { byte[] blk = myConn.PLCGetBlockInMC7(listBox1.SelectedItem.ToString()); System.IO.FileStream _FileStream = new System.IO.FileStream(sav.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); _FileStream.Write(blk, 0, blk.Length); _FileStream.Close(); MessageBox.Show("Block " + listBox1.SelectedItem.ToString() + " saved to: " + sav.FileName); } catch(Exception ex) { MessageBox.Show("Error: " + ex.Message); } } } }
public void CreateReportAsPDF(int? supplierID, long? jobOrderId, string fileName) { try { this.SP_JoGRNTableAdapter.Fill(this.joGRNReportDataSet.SP_JoGRN, supplierID, jobOrderId); // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; reportViewer1.LocalReport.Refresh(); // Setup the report viewer object and get the array of bytes byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); using (System.IO.FileStream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { sw.Write(bytes, 0, bytes.Length); sw.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void GuardarRecursoIncrustado() { // get a reference to the current assembly Assembly a = Assembly.GetExecutingAssembly(); // get a list of resource names from the manifest string [] resNames = a.GetManifestResourceNames(); foreach(string s in resNames) { if (!s.EndsWith("resources") && !s.EndsWith("licenses") && !s.EndsWith("license") && !s.EndsWith("ico")) { if(!System.IO.File.Exists(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"+s)) { System.IO.Stream aStream; aStream = this.GetType().Assembly.GetManifestResourceStream(s); System.IO.FileStream aFileStream=new System.IO.FileStream(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"+s,System.IO.FileMode.Create,System.IO.FileAccess.Write); int Length = 256; Byte [] buffer = new Byte[Length]; int bytesRead = aStream.Read(buffer,0,Length); while( bytesRead > 0 ) { aFileStream.Write(buffer,0,bytesRead); bytesRead = aStream.Read(buffer,0,Length); } aStream.Close(); aFileStream.Close(); } } } }
private void SaveFile(byte[] byteArray) { // Displays a SaveFileDialog so the user can save the Image // assigned to Button2. SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "MCEdit Schematic|*.schematic"; saveFileDialog1.Title = "Save a Schematic File"; saveFileDialog1.ShowDialog(); // If the file name is not an empty string open it for saving. if (saveFileDialog1.FileName != "") { try { // Open file for reading System.IO.FileStream fs = new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); // Writes a block of bytes to this stream using data from a byte array. fs.Write(byteArray, 0, byteArray.Length); // close file stream fs.Close(); } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } } }
//下载网络文件 /// <summary> /// 下载网络文件 带进度条 /// </summary> /// <param name="URL"></param> /// <param name="fileName"></param> /// <param name="progressBar1"></param> /// <returns></returns> public static bool DownloadFile(string URL, string fileName,ProgressBar progressBar1) { try { System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse(); long totalLength = httpWebResponse1.ContentLength; progressBar1.Maximum = (int)totalLength; System.IO.Stream stream1 = httpWebResponse1.GetResponseStream(); System.IO.Stream stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create); long currentLength = 0; byte[] by = new byte[1024]; int osize = stream1.Read(by, 0, (int)by.Length); while (osize > 0) { currentLength = osize + currentLength; stream2.Write(by, 0, osize); progressBar1.Value = (int)currentLength; osize = stream1.Read(by, 0, (int)by.Length); } stream2.Close(); stream1.Close(); return (currentLength == totalLength); } catch { return false; } }
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 ExtractVideoResourceToFile(string targetFile) { // Create temporary output stream file name. System.IO.FileStream file = new System.IO.FileStream( targetFile, System.IO.FileMode.Create); Uri uri = new Uri(ResourceNames.IntroductionVideo, UriKind.RelativeOrAbsolute); StreamResourceInfo resourceInfo = Application.GetResourceStream(uri); System.IO.Stream resourceStream = resourceInfo.Stream; if (null != resourceStream) { try { int offset = 0, bytesRead = 0; byte[] buffer = new byte[4096]; while ((bytesRead = resourceStream.Read(buffer, offset, buffer.Length)) > 0) { file.Write(buffer, offset, bytesRead); } file.Flush(); file.Close(); } catch (Exception) { } } }
//---------- 一些静态方法 ---------- // 下载文件到指定的路径 public static void DownloadFile(string URL, string filename) { try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[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); osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); } catch (Exception ex) { logLog(ex.ToString()); } }
public static bool ByteArrayToFile(string fileName, byte[] data) { try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); // Writes a block of bytes to this stream using data from // a byte array. _FileStream.Write(data, 0, data.Length); // close file stream _FileStream.Close(); return true; } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } // error occured, return false return false; }
public void CreateReportAsPDF(long? orderID, long? orderProductID, string fileName) { try { this.SP_MaterialDetailsTableAdapter.Fill(this.OrderManagerDBDataSet.SP_MaterialDetails, orderProductID, orderID); this.SP_MaterialOtherCostDetailsTableAdapter.Fill(this.OrderManagerDBOtherCostDataSet.SP_MaterialOtherCostDetails, orderProductID); // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; // Setup the report viewer object and get the array of bytes byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); using (System.IO.FileStream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { sw.Write(bytes, 0, bytes.Length); sw.Close(); } } catch (Exception ex) { } }
public static int Execute( List<string> args ) { string Filename = @"c:\Users\Georg\Music\disgaea4\disg4.pak"; string OutPath = @"c:\Users\Georg\Music\disgaea4\"; Console.WriteLine( "Opening " + Filename + "..." ); byte[] b = System.IO.File.ReadAllBytes( Filename ); uint FileAmount = BitConverter.ToUInt32( b, 0 ); for ( int i = 0; i < FileAmount; i++ ) { uint Offset = BitConverter.ToUInt32( b, ( i * 8 ) + 4 ); uint FileSize = BitConverter.ToUInt32( b, ( i * 8 ) + 8 ); String f = OutPath + "0x" + Offset.ToString( "X8" ) + ".ex"; Console.WriteLine( "Writing " + f + "... (" + ( i + 1 ).ToString() + "/" + FileAmount.ToString() + ")" ); System.IO.FileStream fs = new System.IO.FileStream( f, System.IO.FileMode.Create ); fs.Write( b, (int)Offset, (int)FileSize ); } return 0; }
public void CreateReportAsPDF(long? dyeingJoID, string fileName) { try { this.SP_CompactingJoDetailsTableAdapter.Fill(this.CompactingJoDataSet.SP_CompactingJoDetails, dyeingJoID); // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; // Setup the report viewer object and get the array of bytes byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); using (System.IO.FileStream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { sw.Write(bytes, 0, bytes.Length); sw.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void CreateFromDirectory( string Dir, string Outfile ) { string[] Filepaths = System.IO.Directory.GetFiles( Dir ); ushort Filecount = (ushort)Filepaths.Length; uint RequiredBytesForHeader = Util.Align( Filecount * 4u + 4u, 0x50u ); // pretty sure this is not right but should work var Filestream = new System.IO.FileStream( Outfile, System.IO.FileMode.Create ); // header Filestream.WriteByte( (byte)'S' ); Filestream.WriteByte( (byte)'C' ); Filestream.WriteByte( (byte)'M' ); Filestream.WriteByte( (byte)'P' ); uint TotalFilesize = RequiredBytesForHeader; foreach ( string Path in Filepaths ) { Filestream.Write( BitConverter.GetBytes( TotalFilesize ), 0, 4 ); TotalFilesize += (uint)( new System.IO.FileInfo( Path ).Length ); TotalFilesize = TotalFilesize.Align( 0x10u ); } while ( Filestream.Length < RequiredBytesForHeader ) { Filestream.WriteByte( 0x00 ); } // files foreach ( string Path in Filepaths ) { var File = new System.IO.FileStream( Path, System.IO.FileMode.Open ); Util.CopyStream( File, Filestream, (int)File.Length ); File.Close(); while ( Filestream.Length % 0x10 != 0 ) { Filestream.WriteByte( 0x00 ); } } Filestream.Close(); }
public void CreateReportAsPDF(string grnNumbers, string fileName) { try { this.SP_GRNReportTableAdapter.Fill(this.grnReportDataSet.SP_GRNReport, grnNumbers); // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; // Setup the report viewer object and get the array of bytes byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); using (System.IO.FileStream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { sw.Write(bytes, 0, bytes.Length); sw.Close(); } } catch (Exception ex) { } }
public static int Execute( List<string> args ) { string filename = args[0]; uint width = UInt32.Parse( args[1] ); uint height = UInt32.Parse( args[2] ); byte[] data = System.IO.File.ReadAllBytes( filename ); string path = filename + ".dds"; using ( var fs = new System.IO.FileStream( path, System.IO.FileMode.Create ) ) { fs.Write( Textures.DDSHeader.Generate( width, height, 1, format: Textures.TextureFormat.DXT5 ) ); fs.Write( data ); fs.Close(); } return 0; }
public static void SaveToExcel(Microsoft.Reporting.WinForms.ReportViewer reportviewer, string outputfilename) { string deviceinfo = null; string mimetype = null; string encoding = null; string filenamextension = null; string[] streams; Microsoft.Reporting.WinForms.Warning[] warnings; string format = "Excel"; var bytes = reportviewer.LocalReport.Render( format, deviceinfo, out mimetype, out encoding, out filenamextension, out streams, out warnings); using (var fs = new System.IO.FileStream(outputfilename, System.IO.FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); fs.Close(); } }
public void UploadFile(RemoteFileInfo request) { // report start Console.WriteLine("Start uploading " + request.FileName); Console.WriteLine("Size " + request.Length); // create output folder, if does not exist if (!System.IO.Directory.Exists("Upload")) System.IO.Directory.CreateDirectory("Upload"); // kill target file, if already exists string filePath = System.IO.Path.Combine("Upload", request.FileName); if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath); int chunkSize = 2048; byte[] buffer = new byte[chunkSize]; using (System.IO.FileStream writeStream = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)) { do { // read bytes from input stream int bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize); if (bytesRead == 0) break; // write bytes to output stream writeStream.Write(buffer, 0, bytesRead); } while (true); // report end Console.WriteLine("Done!"); writeStream.Close(); } }
// Following example show how to save file and read back from gridfs(using official mongodb driver): // http://www.mongovue.com/ public void Test() { MongoDB.Driver.MongoServer server = MongoServer.Create("mongodb://localhost:27020"); MongoDB.Driver.MongoDatabase database = server.GetDatabase("tesdb"); string fileName = "D:\\Untitled.png"; string newFileName = "D:\\new_Untitled.png"; using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) { MongoDB.Driver.GridFS.MongoGridFSFileInfo gridFsInfo = database.GridFS.Upload(fs, fileName); BsonValue fileId = gridFsInfo.Id; ObjectId oid = new ObjectId(fileId.AsByteArray); MongoDB.Driver.GridFS.MongoGridFSFileInfo file = database.GridFS.FindOne(Query.EQ("_id", oid)); using (System.IO.Stream stream = file.OpenRead()) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); using (System.IO.FileStream newFs = new System.IO.FileStream(newFileName, System.IO.FileMode.Create)) { newFs.Write(bytes, 0, bytes.Length); } // End Using newFs } // End Using stream } // End using fs }
public static void ExtractResourceToFile(byte[] resource, string filename) { if (!System.IO.File.Exists(filename)) using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create)) { fs.Write(resource, 0, resource.Length); } }
public static void writeFile(byte[] bytes, System.String filename, bool append) { //UPGRADE_ISSUE: Constructor 'java.io.FileOutputStream.FileOutputStream' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioFileOutputStreamFileOutputStream_javalangString_boolean"' System.IO.FileStream out_Renamed = new System.IO.FileStream(filename, System.IO.FileMode.Append); out_Renamed.Write((bytes), 0, bytes.Length); out_Renamed.Close(); }
static void Main(string[] args) { try { // open file to output extracted fragments System.IO.FileInfo f1 = new System.IO.FileInfo("./out.txt"); System.IO.FileStream fos = new System.IO.FileStream(f1.FullName, System.IO.FileMode.Create); // instantiate the parser VTDGen vg = new VTDGen(); if (vg.parseFile("./soap2.xml", true)) { VTDNav vn = vg.getNav(); // get to the SOAP header AutoPilot ap = new AutoPilot(); ap.bind(vn); ap.declareXPathNameSpace("ns1", "http://www.w3.org/2003/05/soap-envelope"); // get to the SOAP header ap.selectXPath("/ns1:Envelope/ns1:Header/*[@ns1:mustUnderstand]"); Console.WriteLine("expr string is " + ap.getExprString()); while (ap.evalXPath() != -1) { long l = vn.getElementFragment(); int len = (int)(l >> 32); int offset = (int)l; byte[] b = vn.getXML().getBytes(); fos.Write(b, offset, len); //write the fragment out into out.txt System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("ASCII"); byte[] bytes = encoder.GetBytes("\n=========\n"); fos.Write(bytes, 0, bytes.Length); } fos.Close(); } } catch (NavException e) { System.Console.Out.WriteLine(" Exception during navigation " + e); } catch (System.IO.IOException e) { System.Console.Out.WriteLine(" IO exception condition" + e); } }
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); }
public static void ExtractResourceToFile(string resourceName, string filename) { if (!System.IO.File.Exists(filename)) using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create)) { byte[] b = new byte[s.Length]; s.Read(b, 0, b.Length); fs.Write(b, 0, b.Length); } }
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" } } }; }
/// <summary> /// 把经过base64编码的字符串保存为文件 /// </summary> /// <param name="base64String">经base64加码后的字符串</param> /// <param name="fileName">保存文件的路径和文件名</param> /// <returns>保存文件是否成功</returns> public static bool SaveDecodingToFile(string base64String, string fileName) { using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] b = Convert.FromBase64String(base64String); fs.Write(b, 0, b.Length); // using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) //{ // bw.Write(); // } } return true; }
/// <summary> /// Unpack a PBP file, avoiding to consume too much memory /// (i.e. not reading each section completely in memory). /// </summary> /// <param name="vFile"> the PBP file </param> /// <exception cref="IOException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void unpackPBP(pspsharp.HLE.VFS.IVirtualFile vFile) throws java.io.IOException public static void unpackPBP(IVirtualFile vFile) { vFile.ioLseek(0L); PBP pbp = new PBP(); pbp.size_pbp = (int)vFile.Length(); pbp.p_magic = read32(vFile); if (!pbp.Valid) { return; } pbp.p_version = read32(vFile); pbp.p_offsets = new int[] { read32(vFile), read32(vFile), read32(vFile), read32(vFile), read32(vFile), read32(vFile), read32(vFile), read32(vFile), pbp.size_pbp }; File dir = new File(PBP_UNPACK_PATH_PREFIX); deleteDir(dir); //delete all files and directory dir.mkdir(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'sealed override': //ORIGINAL LINE: sealed override byte[] buffer = new byte[10 * 1024]; sbyte[] buffer = new sbyte[10 * 1024]; for (int index = 0; index < TOTAL_FILES; index++) { int size = pbp.getSize(index); if (size > 0) { long offset = pbp.getOffset(index) & 0xFFFFFFFFL; if (vFile.ioLseek(offset) == offset) { System.IO.Stream os = new System.IO.FileStream(PBP_UNPACK_PATH_PREFIX + pbp.getName(index), System.IO.FileMode.Create, System.IO.FileAccess.Write); while (size > 0) { int Length = System.Math.Min(size, buffer.Length); int readLength = vFile.ioRead(buffer, 0, Length); if (readLength > 0) { os.Write(buffer, 0, readLength); size -= readLength; } if (readLength != Length) { break; } } os.Close(); } } } }
private static void Record(long startTime, long stopTime, string name) { System.IO.FileStream fs = new System.IO.FileStream("E:/Config.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); int r = fs.Read(new byte[102400], 0, 102400); if (r > 0) { fs.WriteByte(13); fs.WriteByte(10); } byte[] buffer = System.Text.Encoding.Default.GetBytes(name + " "+ ", "+ ((float)(stopTime - startTime)) / 10000000); fs.Write(buffer, 0, buffer.Length); fs.Close(); }
public static void WriteSuperblock(System.IO.FileStream fs, Superblock superblock) { fs.Write(BitConverter.GetBytes(superblock.ClusterSize), 0, BitConverter.GetBytes(superblock.ClusterSize).Length); fs.Write(BitConverter.GetBytes(superblock.FSType), 0, BitConverter.GetBytes(superblock.FSType).Length); fs.Write(BitConverter.GetBytes(superblock.INodeCount), 0, BitConverter.GetBytes(superblock.INodeCount).Length); fs.Write(BitConverter.GetBytes(superblock.INodeSize), 0, BitConverter.GetBytes(superblock.INodeSize).Length); fs.Write(BitConverter.GetBytes(superblock.FreeBlock), 0, BitConverter.GetBytes(superblock.FreeBlock).Length); fs.Write(BitConverter.GetBytes(superblock.FreeINode), 0, BitConverter.GetBytes(superblock.FreeINode).Length); }
//</Snippet3> //<Snippet4> public void DecodeWithString() { System.IO.StreamReader inFile; string base64String; try { char[] base64CharArray; inFile = new System.IO.StreamReader(inputFileName, System.Text.Encoding.ASCII); base64CharArray = new char[inFile.BaseStream.Length]; inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length); base64String = new string(base64CharArray); } catch (System.Exception exp) { // Error creating stream or reading from it. System.Console.WriteLine("{0}", exp.Message); return; } // Convert the Base64 UUEncoded input into binary output. byte[] binaryData; try { binaryData = System.Convert.FromBase64String(base64String); } catch (System.ArgumentNullException) { System.Console.WriteLine("Base 64 string is null."); return; } catch (System.FormatException) { System.Console.WriteLine("Base 64 string length is not " + "4 or is not an even multiple of 4."); return; } // Write out the decoded data. System.IO.FileStream outFile; try { outFile = new System.IO.FileStream(outputFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); outFile.Write(binaryData, 0, binaryData.Length); outFile.Close(); } catch (System.Exception exp) { // Error creating stream or writing to it. System.Console.WriteLine("{0}", exp.Message); } }
public void DownloadFileByBlocking(BacnetClient comm, BacnetAddress adr, BacnetObjectId object_id, string filename, Action <int> progress_action) { Cancel = false; //open file System.IO.FileStream fs = null; try { fs = System.IO.File.OpenWrite(filename); } catch (Exception ex) { throw new System.IO.IOException("Couldn't open file", ex); } int position = 0; uint count = (uint)comm.GetFileBufferMaxSize(); bool end_of_file = false; byte[] buffer; int buffer_offset; try { while (!end_of_file && !Cancel) { //read from device if (!comm.ReadFileRequest(adr, object_id, ref position, ref count, out end_of_file, out buffer, out buffer_offset)) { throw new System.IO.IOException("Couldn't read file"); } position += (int)count; //write to file if (count > 0) { fs.Write(buffer, buffer_offset, (int)count); if (progress_action != null) { progress_action(position); } } } } finally { fs.Close(); } }
public ActionResult CropImage( string imagePath, int?cropPointX, int?cropPointY, int?imageCropWidth, int?imageCropHeight) { if (string.IsNullOrEmpty(imagePath) || !cropPointX.HasValue || !cropPointY.HasValue || !imageCropWidth.HasValue || !imageCropHeight.HasValue) { return(new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest)); } byte[] imageBytes = System.IO.File.ReadAllBytes(Server.MapPath(imagePath)); byte[] croppedImage = cms_db.CropImage(imageBytes, cropPointX.Value, cropPointY.Value, imageCropWidth.Value, imageCropHeight.Value); long idUser = long.Parse(User.Identity.GetUserId()); try { if (croppedImage != null) { MediaContent CurrentMediaId = cms_db.GetObjMedia().Where(s => s.ObjTypeId == (int)EnumCore.ObjTypeId.nguoi_dung && s.ContentObjId == idUser).FirstOrDefault(); string userPhotoUrl = "~/" + CurrentMediaId.FullURL; System.IO.FileStream _FileStream = new System.IO.FileStream(Server.MapPath(userPhotoUrl), System.IO.FileMode.Create, System.IO.FileAccess.Write); _FileStream.Write(croppedImage, 0, croppedImage.Length); _FileStream.Close(); return(Json("{\"photo_url\": \"" + CurrentMediaId.FullURL + "\", \"result\": \"1\"}")); } else { return(Json("{\"photo_url\": \"" + "/Media/no_photo.png" + "\", \"result\": \"0\"}")); } } catch (Exception ex) { DataModel.DataStore.Core core = new DataModel.DataStore.Core(); core.AddToExceptionLog("UpdatePhotoUser", "AccountController", "Upload photo Error: " + ex.Message, idUser); return(Json("{\"photo_url\": \"" + "/Media/no_photo.png" + "\", \"result\": \"0\"}")); } }
private static void Write(string outputFile, string[] resultStrings) { // Create the file, or overwrite if the file exists. using (System.IO.FileStream fs = System.IO.File.Create(outputFile)) { foreach (string resultString in resultStrings) { byte[] info = new System.Text.UTF8Encoding(true).GetBytes(resultString + '\n'); // Add information to the file. int offset = 0; fs.Write(info, offset, info.Length); offset += info.Length; } } }
//Copies fixed amount of bytes starting from fs1 current position public static long CopyBytes(System.IO.FileStream fs1, System.IO.FileStream fs2, long bytesToCopy, int blockSize) { long bytesWritten = 0; try { while (bytesToCopy - bytesWritten >= blockSize) { var block = ByteReader.ReadBlock(fs1, blockSize); fs2.Write(block, 0, block.Length); bytesWritten += block.Length; } var lastBytes = ByteReader.ReadBytes(fs1, bytesToCopy - bytesWritten); fs2.Write(lastBytes, 0, lastBytes.Length); bytesWritten += lastBytes.Length; } catch (Exception e) { Logger.GetInstance("").Log(e.Message + Environment.NewLine); throw e; } return(bytesWritten); }
private void ultraButton2_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(ultraTextEditor3.Text.Trim()) || String.IsNullOrEmpty(ultraTextEditor4.Text.Trim())) { return; } List <FileInfo> fileInfoList = this.FindList <FileInfo>(Globals.FILETRANSFER_SERVICE_NAME, "download", new object[] { ultraTextEditor3.Text.Trim() }); foreach (FileInfo fileInfo in fileInfoList) { System.IO.FileStream stream = new System.IO.FileStream(ultraTextEditor4.Text.Trim() + System.IO.Path.DirectorySeparatorChar + fileInfo.Name, System.IO.FileMode.OpenOrCreate); stream.Write(fileInfo.Content, 0, fileInfo.Content.Length); stream.Close(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void writeBytes(File file, byte[] data) throws FileNotFoundException public static void writeBytes(File file, sbyte[] data) { try { using (System.IO.FileStream os = new System.IO.FileStream(file, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { os.Write(data, 0, data.Length); } } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } }
static void Main(string[] args) { if (args.Length < 2) { return; } System.IO.FileStream fs = System.IO.File.OpenRead(args[0]); byte[] t = LB_ZIP.LB_ZIP.Zip(fs, (int)fs.Length); fs.Close(); System.IO.FileStream fs_out = System.IO.File.Create(args[1]); fs_out.Write(t, 0, t.Length); fs_out.Close(); }
bool IActor.OnMessageRecieved <T>(T msg) { if (!(msg as IActorMessage).Message.GetType().Name.Equals("Byte[]")) { throw new SendBytesCanOnlySendValueTypeByteArrayMessagesException("ValueTypeMessage<byte>"); } byte[] msgBytes = (byte[])msg.Message; using (System.IO.FileStream fs = System.IO.File.Open(this.pathToFile, System.IO.FileMode.OpenOrCreate)) { fs.Position = fs.Length; fs.Write(msgBytes, 0, msgBytes.Length); } return(true); }
private void DumpBlocks() { System.IO.Directory.CreateDirectory("Debug"); string positions = ""; for (int i = 0; i < result.Count; i++) { var stream = new System.IO.FileStream("Debug/" + i.ToString() + ".bin", System.IO.FileMode.OpenOrCreate); stream.Write(result.Blocks[i], 0, result.Sizes[i]); stream.Close(); positions += i + "=" + System.Convert.ToString(result.Positions[i], 16) + "\n"; } System.IO.File.WriteAllText("positions.txt", positions); System.IO.File.WriteAllBytes("Debug/TrashHeader.bin", result.TrashHeader); }
/// <summary>output methods: </summary> public override void FlushBuffer(byte[] b, int offset, int size) { file.Write(b, offset, size); // {{dougsale-2.4.0}} // FSIndexOutput.Flush // When writing frequently with small amounts of data, the data isn't flushed to disk. // Thus, attempting to read the data soon after this method is invoked leads to // BufferedIndexInput.Refill() throwing an IOException for reading past EOF. // Test\Index\TestDoc.cs demonstrates such a situation. // Forcing a flush here prevents said issue. // {{DIGY 2.9.0}} // This code is not available in Lucene.Java 2.9.X. // Can there be a indexing-performance problem? file.Flush(); }
/// <summary> /// Scrive un file in PDF /// </summary> /// <param name="file">Array di byte di cui è formato il file</param> /// <param name="name">Nome del file da salvare</param> public static void PDFtoFile(byte[] file, string name) { System.IO.FileInfo fi = new System.IO.FileInfo(name); if (fi.Exists) { fi.Delete(); } using (System.IO.FileStream fs = System.IO.File.Create(name)) { fs.Write(file, 0, file.Length); fs.Close(); } }
public async Task Download(File file, string path) { labelAction.Text = "Downloading..."; labelContent.Text = file.Path; byte[] data = await file.Download(); using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create)) { if (data != null) { fs.Write(data, 0, data.Length); } } Close(); }
/// <summary> /// /// </summary> /// <param name="informations"></param> /// <param name="savePath"></param> public static void SaveConfigureInfos(ConfigureInfosStrcut informations, string savePath) { SoapFormatter oXmlFormatter = new SoapFormatter(); System.IO.MemoryStream oMemStream = new System.IO.MemoryStream(); oXmlFormatter.Serialize(oMemStream, informations); System.IO.FileStream oFileStream = new System.IO.FileStream(savePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); byte[] oBytes = oMemStream.GetBuffer(); oFileStream.Write(oBytes, 0, oBytes.Length); oFileStream.Close(); }
void OnSaveAsFile() { var filePath = EditorUtility.SaveFilePanel("Save", "", m_Selected.name.Replace('.', '_'), "mem"); if (string.IsNullOrEmpty(filePath)) { return; } using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate)) { var bytes = m_Selected.packed.staticFieldBytes; fileStream.Write(bytes, 0, bytes.Length); } }
public static void WriteAllBytes(string path, byte[] bytes) { if (path.Length < MAX_PATH) { System.IO.File.WriteAllBytes(path, bytes); } else { var fileHandle = CreateFileForWrite(GetWin32LongPath(path)); using (var fs = new System.IO.FileStream(fileHandle, System.IO.FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); } } }
/// <summary> /// 将字符串写入文件 /// </summary> /// <param name="s"></param> /// <param name="fs"></param> internal static void StrToFile(string s, System.IO.FileStream fs) { //throw new NotImplementedException(); try { fs.Position = fs.Length; Encoding enc = Encoding.UTF8; byte[] str = enc.GetBytes(s); fs.Write(str, 0, str.Length); fs.Close(); } catch { } }
private void SendConfirmation(string to, string text) { string filename = @"C:\Users\99555\source\repos\muscshop\Content\Registration.txt"; if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } using (System.IO.FileStream fs = System.IO.File.Create(filename)) { byte[] innerText = new UTF8Encoding(true).GetBytes(text); fs.Write(innerText, 0, innerText.Length); } }
public static void savebiosflashfile(string name) //save flash ram file { try { System.IO.FileInfo fi = new System.IO.FileInfo(name); System.IO.FileStream fs = fi.OpenWrite(); fs.Write(bios_flash, 0, 256 * kb); fs.Close(); dc.dcon.WriteLine("Flash ram saved to \"" + name + "\""); } catch { dc.dcon.WriteLine("Flash ram cannot be saved to \"" + name + "\""); } }
private void SendMail(string to, string text) { string filename = @"C:\Users\Yakimas\Desktop\Register.txt"; if(System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } using (System.IO.FileStream fs = System.IO.File.Create(filename)) { byte[] innerText = new UTF8Encoding(true).GetBytes(text); fs.Write(innerText, 0, innerText.Length); } }
public static void WriteStructToFile(string filename) { string saveToFilePath = @"D:\" + filename; int bytesWritten = 0; using (System.IO.FileStream myFileStream = new System.IO.FileStream(saveToFilePath, System.IO.FileMode.Create)) { BMPHeader myData = new BMPHeader(); byte[] newBuffer = GetBytes <BMPHeader>(myData); myFileStream.Write(newBuffer, 0, newBuffer.Length); bytesWritten += newBuffer.Length; } }
/// <summary> /// Helper function to generate a temporary file with the given content and extension. /// </summary> /// <param name="text">File content.</param> /// <param name="ext">File extension.</param> /// <returns></returns> private String internalCreateTestFile(String text, String ext) { String tempName = internalMakeTempFileName(ext); System.IO.FileStream fstrm = new System.IO.FileStream(tempName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); int n = encoding.GetByteCount(text); byte[] buf = new byte[n]; encoding.GetBytes(text, 0, text.Length, buf, 0); fstrm.Write(buf, 0, buf.Length); fstrm.Close(); return(tempName); }
private static void copyStreamToFile(System.IO.Stream stream, string destination) { using (System.IO.BufferedStream bs = new System.IO.BufferedStream(stream)) { using (System.IO.FileStream os = System.IO.File.OpenWrite(destination)) { byte[] buffer = new byte[2 * 4096]; int nBytes; while ((nBytes = bs.Read(buffer, 0, buffer.Length)) > 0) { os.Write(buffer, 0, nBytes); } } } }
protected void Process(object _) { try { string ufile = System.IO.Path.Combine(_sys, "AutoUpdate.zip"); if (!System.IO.File.Exists(ufile)) { MessageLaunchAndExit("Couldn't find update file."); return; } byte[] buffer = new byte[0x10000]; using (SharpCompress.Archives.Zip.ZipArchive zip = SharpCompress.Archives.Zip.ZipArchive.Open(ufile)) { foreach (var entry in zip.Entries.Where(e => !e.IsDirectory)) { using (var s = entry.OpenEntryStream()) { Status("Updating " + entry.Key); foreach (int i in Enumerable.Range(0, 5)) { try { using (var fs = new System.IO.FileStream(System.IO.Path.Combine(_7h, entry.Key), System.IO.FileMode.Create)) { int len; while ((len = s.Read(buffer, 0, buffer.Length)) != 0) { fs.Write(buffer, 0, len); } } break; } catch (System.IO.IOException) { if (i < 4) { Status(entry.Key + " ...file in use; waiting."); System.Threading.Thread.Sleep(1000); continue; } } if (i == 4) { MessageLaunchAndExit("Update incomplete - could not update all files"); } } } } } Status("Update complete, removing download"); System.IO.File.Delete(ufile); MessageLaunchAndExit("Update complete!"); } catch (Exception ex) { MessageLaunchAndExit("Error applying update: " + ex.ToString()); } }
public static void Unzip(string input, string output) { string path = output; if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString())) { path += System.IO.Path.DirectorySeparatorChar; } using (System.IO.FileStream fileStream = System.IO.File.OpenRead(input)) { NZlib.Zip.ZipInputStream zipInputStream = new NZlib.Zip.ZipInputStream(fileStream); NZlib.Zip.ZipEntry zipEntry; int size = 2048; byte[] data = new byte[2048]; while ((zipEntry = zipInputStream.GetNextEntry()) != null) { System.IO.FileInfo fileinfo = new System.IO.FileInfo(path + zipEntry.Name); if (!fileinfo.Directory.Exists) { fileinfo.Directory.Create(); } System.IO.FileStream outputFileStream = System.IO.File.Create(path + zipEntry.Name); while (true) { size = zipInputStream.Read(data, 0, data.Length); if (size > 0) { outputFileStream.Write(data, 0, size); } else { break; } } outputFileStream.Flush(); outputFileStream.Close(); } zipInputStream.Close(); fileStream.Close(); } }
public void Invoke() { using (AesCng aes = new AesCng()) { Console.Write("Enter Key Password: "******"Confirm Password: "******"Passwords did not match."); return; } CngKey pk = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521, null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }); byte[] publicKeyBlock = pk.Export(CngKeyBlobFormat.EccPublicBlob); byte[] privateKeyBlob = pk.Export(CngKeyBlobFormat.EccPrivateBlob); aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; aes.IV = IV; aes.Key = HashString(p1); byte[] decryptedECPrivateBlob = new byte[EncryptedECPrivateBlobLength]; Buffer.BlockCopy(privateKeyBlob, 0, decryptedECPrivateBlob, 0, privateKeyBlob.Length); byte[] encryptedData = null; using (var encryptor = aes.CreateEncryptor()) { encryptedData = encryptor.TransformFinalBlock(decryptedECPrivateBlob, 0, decryptedECPrivateBlob.Length); } using (var file = new System.IO.FileStream(PublicKeyFile, System.IO.FileMode.CreateNew)) using (var writer = new System.IO.BinaryWriter(file)) { writer.Write((int)FileType.Public); file.Write(publicKeyBlock, 0, publicKeyBlock.Length); } using (var file = new System.IO.FileStream(PrivateKeyFile, System.IO.FileMode.CreateNew)) using (var writer = new System.IO.BinaryWriter(file)) { writer.Write((int)FileType.Private); writer.Write(encryptedData, 0, encryptedData.Length); } Console.WriteLine($"Thumbprint: {new KeyThumbprint(pk)}"); } }
public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera) { try { System.IO.FileStream fos = new System.IO.FileStream(_filePath, System.IO.FileMode.Create); fos.Write(data, 0, data.Length); fos.Flush(); fos.Close(); ExifInterface exif = new ExifInterface(_filePath); if (exif != null) { int exifroation = 1; switch (_rotation) { case 90: exifroation = 6; break; case 180: exifroation = 3; break; case 270: exifroation = 8; break; default: exifroation = 1; break; } exif.SetAttribute(ExifInterface.TagOrientation, Convert.ToString(exifroation)); exif.SaveAttributes(); int orientation = Convert.ToInt16(exif.GetAttributeInt(ExifInterface.TagOrientation, (int)0)); System.Diagnostics.Debug.WriteLine(orientation); } OnPictureTakenCompleted(EventArgs.Empty); } catch (FileNotFoundException ex) { string message = ex.Message; //Log.Debug(TAG, "File not found: " + ex.getMessage()); } catch (IOException ex) { string message = ex.Message; //Log.Debug(Tag, "Error accessing file: " + ex.getMessage()); } }