/// <summary> /// regisztrációs file elkészítése /// </summary> /// <param name="registrationFileNameWithPath"></param> /// <param name="htmlContent"></param> public void CreateRegistrationFile(string registrationFileNameWithPath, string htmlContent) { //using (FileStream fs = new FileStream("test.htm", FileMode.Create)) //{ // using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) // { // w.WriteLine("<H1>Hello</H1>"); // } //} try { Helpers.DesignByContract.Require(!String.IsNullOrEmpty(registrationFileNameWithPath), "Registration file name with path cannot be null or empty!"); System.IO.FileStream fs = new System.IO.FileStream(registrationFileNameWithPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); //System.IO.FileShare.Write, System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fs, System.Text.Encoding.GetEncoding(28592)); System.IO.StringWriter stringWriter = new System.IO.StringWriter(); stringWriter.Write(htmlContent); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(stringWriter); streamWriter.WriteLine(stringWriter.ToString()); streamWriter.Close(); } catch (Exception ex) { throw ex; } }
public byte[] FileToByteArray(string _FileName) { byte[] _Buffer = null; try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach filestream to binary reader System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); // get total byte length of the file long _TotalBytes = new System.IO.FileInfo(_FileName).Length; // read entire file into buffer _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes)); // close file reader _FileStream.Close(); _FileStream.Dispose(); _BinaryReader.Close(); } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } return _Buffer; }
/// <summary> /// Компрессия или декомпрессия файла /// </summary> /// <param name="fromFile">Исходный файл для компрессии или декомпрессии</param> /// <param name="toFile">Целевой файл</param> /// <param name="compressionMode">Указывает на компрессию или декомпрессию</param> private static void CompressOrDecompressFile(string fromFile, string toFile, System.IO.Compression.CompressionMode compressionMode) { System.IO.FileStream toFs = null; System.IO.Compression.GZipStream gzStream = null; System.IO.FileStream fromFs = new System.IO.FileStream(fromFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); try { toFs = new System.IO.FileStream(toFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); gzStream = new System.IO.Compression.GZipStream(toFs, compressionMode); byte[] buf = new byte[fromFs.Length]; fromFs.Read(buf, 0, buf.Length); gzStream.Write(buf, 0, buf.Length); } finally { if (gzStream != null) gzStream.Close(); if (toFs != null) toFs.Close(); fromFs.Close(); } }
private static void RunTime() { TimeOptions options = new TimeOptions(); string[] timeArgs = new string[] { "-v", "-o", "/path/to/file", "-a", "--", "--some--", "useless", "noise" }; options.Initialize(timeArgs); /* TimeOptions processing to be added */ string format = options.format; if (options.portability) { if (options.verbose) { Console.WriteLine("Setting portable format."); } format = PORTABLE_FORMAT; } System.IO.StreamWriter writer = null; if (options.outputFile != null && System.IO.File.Exists(options.outputFile)) { var fileStream = new System.IO.FileStream(options.outputFile, options.append ? System.IO.FileMode.Append : System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); writer = new System.IO.StreamWriter(fileStream); if (options.verbose) { Console.WriteLine("Output will be redirected to file."); } } else if (options.verbose) { Console.WriteLine("Output will be printed to standart output."); } DoCoreTask(options.Arguments, writer, format); if (writer != null) { writer.Flush(); writer.Close(); } }
//Code PES private string GetBuildNumber() { string strBuildNumber = string.Empty, timestamp = string.Empty; string filePath = System.Reflection.Assembly.GetCallingAssembly().Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] b = new byte[2048]; System.IO.Stream s = null; try { s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); s.Read(b, 0, 2048); } finally { if (s != null) { s.Close(); } } int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset); int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset); DateTime dtDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dtDate = dtDate.AddSeconds(secondsSince1970); dtDate = dtDate.ToLocalTime(); timestamp = dtDate.ToString("yyyyMMddHHmmss"); if (timestamp == string.Empty) { timestamp = "UNKOWN!"; } strBuildNumber = "Build : " + timestamp; return strBuildNumber; }
public static int Execute( List<string> args ) { if ( args.Count < 2 ) { Console.WriteLine( "Usage: ByteHotfix [filename] [location-byte] [location-byte] etc." ); Console.WriteLine( "example: ByteHotfix 325.new 3A9A3-94 3AA72-A4 3AA73-32 3AB53-51" ); return -1; } /* args = new string[] { @"c:\#gn_chat\scenario.dat.ext.ex\325.new" , "3A9A3-94", "3AA72-A4", "3AA73-32", "3AB53-51" }; */ try { string inFilename = args[0]; using ( var fi = new System.IO.FileStream( inFilename, System.IO.FileMode.Open ) ) { for ( int i = 1; i < args.Count; i++ ) { String[] v = args[i].Split( new char[] { '-' } ); int location = int.Parse( v[0], NumberStyles.AllowHexSpecifier ); byte value = byte.Parse( v[1], NumberStyles.AllowHexSpecifier ); fi.Position = location; fi.WriteByte( value ); } fi.Close(); } return 0; } catch ( Exception ex ) { Console.WriteLine( "Exception: " + ex.Message ); return -1; } }
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) { } }
private void loadToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { SkeletDrawInfo _sdi; System.IO.Stream stream = new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); try { _sdi = (SkeletDrawInfo)formatter.Deserialize(stream); if (_sdi.nodes.Length == skelet.bones.Length && _sdi.relations.Length == sdi.relations.Length) { _sdi.sk = skelet; for (int o = 0; o < _sdi.nodes.Length; o++) _sdi.nodes[o].bone = skelet.bones[_sdi.nodes[o].index]; sdi = _sdi; Invalidate(); } } catch (System.Runtime.Serialization.SerializationException) { System.Windows.Forms.MessageBox.Show("Wrong file format"); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } finally { stream.Close(); } } }
/// <summary> /// 根据文件的前2个字节进行判断文件类型 ---说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar /// </summary> /// <param name="hpf"></param> /// <param name="code">文件的前2个字节转化出来的小数</param> /// <returns></returns> public bool CheckUploadByTwoByte(HttpPostedFile hpf, Int64 code) { System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader r = new System.IO.BinaryReader(fs); string fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { } r.Close(); fs.Close(); // //if (fileclass == code.ToString()) //{ // return true; //} //else //{ // return false; //} return (fileclass == code.ToString()); }
private static void OtherWaysToGetReport() { string report = @"d:\bla.rdl"; // string lalal = System.IO.File.ReadAllText(report); // byte[] foo = System.Text.Encoding.UTF8.GetBytes(lalal); // byte[] foo = System.IO.File.ReadAllBytes(report); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.IO.FileStream file = new System.IO.FileStream(report, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); ms.Write(bytes, 0, (int)file.Length); ms.Flush(); ms.Position = 0; } using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("resource")) { using (System.IO.TextReader reader = new System.IO.StreamReader(ms)) { // rv.LocalReport.LoadReportDefinition(reader); } } using (System.IO.TextReader reader = System.IO.File.OpenText(report)) { // rv.LocalReport.LoadReportDefinition(reader); } } }
protected override void Save() { if (!this.infoLoaded) return; RGSSTable table = new RGSSTable(this.Size.Width, this.Size.Height, this.Layers.Count); List<MapLayer> truth = new List<MapLayer>(this.Layers); if (truth.Count == 4) { MapLayer layer = truth[2]; truth.Remove(layer); truth.Add(layer); } for (int z = 0; z < truth.Count; z++) { for (int x = 0; x < this.Size.Width; x++) { for (int y = 0; y < this.Size.Height; y++) { table[x, y, z] = truth[z].Data[x, y]; } } } raw.InstanceVariable["@data"] = table; using (var fs = new System.IO.FileStream(this.filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { NekoKun.Serialization.RubyMarshal.RubyMarshal.Dump(fs, raw); } }
private static void LoadOptions() { try { string path = AppDomain.CurrentDomain.BaseDirectory + System.IO.Path.DirectorySeparatorChar + "options.config"; if (System.IO.File.Exists(path)) { using (System.IO.Stream s = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { options_ = xs_.Deserialize(s) as MFOptions; } } } catch(Exception ex) { System.Diagnostics.Trace.WriteLine(ex); options_ = new MFOptions(); } }
//下载网络文件 /// <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; } }
private void SaveWebPost(string fileName, PostModel model) { WebPostModel wPost = new WebPostModel() { PTitle = model.PTitle, PText = model.PText, PLink = model.PLink, PImage = model.PImage, PDate = model.PDate.ToString("yyyy-MM-ddTHH:mm:ss"), PPrice = model.PPrice }; System.IO.MemoryStream msPost = new System.IO.MemoryStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer dcJsonPost = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WebPostModel)); dcJsonPost.WriteObject(msPost, wPost); using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] jsonArray = msPost.ToArray(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress)) { gz.Write(jsonArray, 0, jsonArray.Length); } } }
private DateTime RetrieveLinkerTimestamp() { string filePath = System.Reflection.Assembly.GetCallingAssembly().Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] b = new byte[2048]; System.IO.Stream s = null; try { s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); s.Read(b, 0, 2048); } finally { if (s != null) { s.Close(); } } int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset); int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset); DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0); dt = dt.AddSeconds(secondsSince1970); dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours); return dt; }
public void getPdfFile(string fileName) { using (SqlConnection cn = new SqlConnection(ConnectionString)) { cn.Open(); using (SqlCommand cmd = new SqlCommand($"select FileSource from PdfDocumentFiles where Name='{fileName}' ", cn)) { using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.Default)) { if (dr.Read()) { byte[] fileData = (byte[])dr.GetValue(0); using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData); bw.Close(); } } } dr.Close(); } } } }
// GET: Api/Post/Add3 public JsonResult Add3() { PostModel model = new PostModel(); model.PDate = DateTime.Now; string fileName = Server.MapPath("~/App_Data/test3.json"); model.PText = fileName; System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PostModel)); System.IO.MemoryStream stream1 = new System.IO.MemoryStream(); ser.WriteObject(stream1, model); using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] jsonArray = stream1.ToArray(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress)) { gz.Write(jsonArray, 0, jsonArray.Length); } } return Json(model, JsonRequestBehavior.AllowGet); }
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 bool ByteArrayToFile(string _FileName, byte[] _ByteArray) { try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(_FileStream); // Writes a block of bytes to this stream using data from // a byte array. bw.Write(_ByteArray, 0, _ByteArray.Length); // close file stream bw.Close(); return true; } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } // error occured, return false return false; }
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 btnOpenStream_Click(object sender, EventArgs e) { //open a doc document OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*"; dialog.Title = "Select a DOC file"; dialog.Multiselect = false; dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data"); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { string docFile = dialog.FileName; stream = new System.IO.FileStream(docFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); if (stream != null) { //Load doc document from stream. this.docDocumentViewer1.LoadFromStream(stream, Spire.Doc.FileFormat.Auto); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
protected YUVFile(string path, Int32 width, Int32 height) { File = System.IO.File.OpenRead(path); Height = height; Width = width; Square = height * width; }
public void InitializeTwitter() { try { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(saveSettings)); System.IO.FileStream fs = new System.IO.FileStream( @"settings.xml", System.IO.FileMode.Open); saveSettings setting = (saveSettings)serializer.Deserialize(fs); fs.Close(); textBox1.Enabled = false; //accToken = setting.AccToken; token.AccessToken = setting.AccToken; //accTokenSec = setting.AccTokenSec; token.AccessTokenSecret = setting.AccTokenSec; var Stream = new TwitterStream(token, "Feedertter", null); StatusCreatedCallback statusCreatedCallback = new StatusCreatedCallback(StatusCreatedCallback); RawJsonCallback rawJsonCallback = new RawJsonCallback(RawJsonCallback); Stream.StartUserStream(null, null, /*(x) => { label1.Text += x.Text; }*/ statusCreatedCallback, null, null, null, null, rawJsonCallback); } catch { Process.Start(OAuthUtility.BuildAuthorizationUri(req.Token).ToString()); } //Process.Start(OAuthUtility.BuildAuthorizationUri(req.Token).ToString()); }
public static MidiData parse(FileStream input_file_stream) { var input_binary_reader = new BinaryReader(input_file_stream); HeaderChunk header_chunk; ushort number_of_tracks; { var header_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4)); var header_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray<byte>(), 0); var header_chunk_data = input_binary_reader.ReadBytes(header_chunk_size); var format_type = BitConverter.ToUInt16(header_chunk_data.Take(2).Reverse().ToArray<byte>(), 0); number_of_tracks = BitConverter.ToUInt16(header_chunk_data.Skip(2).Take(2).Reverse().ToArray<byte>(), 0); var time_division = BitConverter.ToUInt16(header_chunk_data.Skip(4).Take(2).Reverse().ToArray<byte>(), 0); header_chunk = new HeaderChunk(format_type, time_division); } var tracks = Enumerable.Range(0, number_of_tracks) .Select(track_number => { var track_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4)); var track_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray<byte>(), 0); var track_chunk_data = input_binary_reader.ReadBytes(track_chunk_size); return Tuple.Create(track_chunk_size, track_chunk_data); }).ToList() .Select(raw_track => new TrackChunk(parse_events(raw_track.Item2, raw_track.Item1))); return new MidiData(header_chunk, tracks); }
/// <summary> /// Returns the path to the sketch image just created /// <param name="mask">Mask image of the button</param> /// <param name="texture">Texture image of the item</param> /// <param name="nameSketch">Name of the image to create</param> public static string CreateSketchesPath(string mask, string texture, string nameSketch) { MagickImage Mask = new MagickImage(mask); MagickImage Texture = new MagickImage(texture); Texture.Crop(Mask.Width, Mask.Height); Texture.Composite(Mask, CompositeOperator.CopyAlpha); Mask.Composite(Texture, CompositeOperator.Multiply); MagickImage sketch = Mask; try { // sketch.Write(Helpers.ResourcesHelper.SketchesPath() + nameSketch); string p = Helpers.ResourcesHelper.SketchesPath() + nameSketch; System.IO.Stream s = new System.IO.FileStream(p, System.IO.FileMode.Create); sketch.Write(s); s.Close(); } catch (MagickException ex) { string s= ex.Message; } catch { } sketch.Dispose(); sketch = null; string path = Helpers.ResourcesHelper.SketchesPath() + nameSketch; return path; }
private void button1_Click(object sender, RoutedEventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.FileName = "result.csv"; dialog.Filter = "CSVファイル(*.csv)|*.csv|全てのファイル(*.*)|*.*"; dialog.OverwritePrompt = true; dialog.CheckPathExists = true; bool? res = dialog.ShowDialog(); if (res.HasValue && res.Value) { try { if (mainWin.fileWriter != null) mainWin.fileWriter.Flush(); System.IO.Stream fstream = dialog.OpenFile(); System.IO.Stream fstreamAppend = new System.IO.FileStream(dialog.FileName+"-log.csv", System.IO.FileMode.OpenOrCreate); if (fstream != null && fstreamAppend != null) { textBox1.Text = dialog.FileName; mainWin.fileWriter = new System.IO.StreamWriter(fstream); mainWin.logWriter = new System.IO.StreamWriter(fstreamAppend); } } catch (Exception exp) { MessageBox.Show(exp.ToString()); } } }
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(); } }
private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { //Открываем файл картинки... System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open); System.Drawing.Image img = System.Drawing.Image.FromStream(fs); fs.Close(); //Помещаем исходное изображение в PictureBox1 pictureBox1.Image = img; var bmp = new Bitmap(img); label1.Text = ""; label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString() + " - "; //Время начала обработки (секунды и миллисекунды). //Преобразуем картинку MakeGray(bmp); //Crop(bmp, new Rectangle(0, 0, bmp.Height, bmp.Width)); Bitmap cropBmp = bmp.Clone(new Rectangle(0, 0, bmp.Width / 2, bmp.Height / 2), bmp.PixelFormat); label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString(); //Время окончания обработки (секунды и миллисекунды). //Помещаем преобразованное изображение в PictureBox2 pictureBox2.Image = cropBmp; Bitmap cropcloneBmp = cropBmp.Clone(new Rectangle(0, 0, cropBmp.Width, cropBmp.Height), cropBmp.PixelFormat); MakeGray(cropcloneBmp); //Crop(bmp, new Rectangle(0, 0, bmp.Height, bmp.Width)); Bitmap cropnewBmp = cropcloneBmp.Clone(new Rectangle(0, 0, cropcloneBmp.Width / 2, cropcloneBmp.Height / 2), cropcloneBmp.PixelFormat); label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString(); //Время окончания обработки (секунды и миллисекунды). //Помещаем преобразованное изображение в PictureBox2 pictureBox3.Image = cropnewBmp; } }
public void Load() { System.IO.FileStream file = new System.IO.FileStream("data.dat",System.IO.FileMode.Open ) ; Byte[] buffer1 = System.BitConverter.GetBytes( Existe[0] ) ; Byte[] buffer2 = System.BitConverter.GetBytes( Left[0] ) ; Byte[] buffer3 = System.BitConverter.GetBytes( Top[0] ) ; Byte[] buffer4 = System.BitConverter.GetBytes( Color[0].ToArgb() ) ; Byte[] buffer5 = System.Text.Encoding.BigEndianUnicode.GetBytes( Text[0], 0 , Text[0].Length ) ; Byte[] bufferM1 = System.BitConverter.GetBytes( MainLeft ) ; Byte[] bufferM2 = System.BitConverter.GetBytes( MainTop ) ; file.Read( bufferM1, 0, bufferM1.Length ) ; MainLeft = System.BitConverter.ToInt32( bufferM1 , 0 ) ; file.Read( bufferM2, 0, bufferM2.Length ) ; MainTop = System.BitConverter.ToInt32( bufferM2 , 0 ) ; for ( int i = 0 ; i < MAX_POSTS ; i++ ) { file.Read( buffer1, 0, buffer1.Length ) ; Existe[i] = System.BitConverter.ToBoolean( buffer1 , 0 ) ; file.Read( buffer2, 0, buffer2.Length ) ; Left[i] = System.BitConverter.ToInt32( buffer2 , 0 ) ; file.Read( buffer3, 0, buffer3.Length ) ; Top[i] = System.BitConverter.ToInt32( buffer3 , 0 ) ; file.Read( buffer4, 0, buffer4.Length ) ; Color[i] = System.Drawing.Color.FromArgb( System.BitConverter.ToInt32(buffer4, 0 ) ) ; file.Read( buffer5, 0, buffer5.Length ) ; Text[i] = System.Text.Encoding.BigEndianUnicode.GetChars( buffer5 ) ; } file.Close() ; }
static byte[] readFile(string filename) { //let readFile filename = //// let f = new IO.BufferedStream(new IO.FileStream(filename, IO.FileMode.Open, System.IO.FileAccess.Read)) // let f = new IO.FileStream(filename, IO.FileMode.Open, System.IO.FileAccess.Read) // let fileSize = f.Length |> int // let buf = Array.create(fileSize) 0uy // 符号なし 8 ビット自然数?? http://msdn.microsoft.com/ja-jp/library/dd233193.aspx // let mutable remain = fileSize; // let mutable bufPos = 0; // while remain > 0 do // let readSize = f.Read(buf, bufPos, System.Math.Min(1024, remain)) // bufPos <- bufPos + readSize // remain <- remain - readSize // buf var f = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); var fileSize = (int)f.Length; var buf = new byte[fileSize]; int bufPos = 0; while (fileSize > 0) { int readSize = f.Read(buf, bufPos, System.Math.Min(1024, fileSize)); bufPos += readSize; fileSize -= readSize; } return buf; }
static void Main(string[] args) { const int PORT = 8810; if (args.Length == 1) { uint msgId = 0; string dir = args[0]; System.Net.Sockets.TcpListener server = null; try { System.Net.IPEndPoint localAddress = new System.Net.IPEndPoint(0, PORT); server = new System.Net.Sockets.TcpListener(localAddress); server.Start(); System.Console.WriteLine("파일 다운로드 대기 중..."); while (true) { System.Net.Sockets.TcpClient client = server.AcceptTcpClient(); System.Console.WriteLine("{0} 연결", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).ToString()); System.Net.Sockets.NetworkStream stream = client.GetStream(); FUP.Message reqMsg = FUP.MessageUtil.Receive(stream); if (reqMsg.Header.MSGTYPE != FUP.CONSTANTS.REQ_FILE_SEND) { stream.Close(); client.Close(); continue; } FUP.BodyRequest reqBody = (FUP.BodyRequest)reqMsg.Body; System.Console.WriteLine("파일 전송 요청이 왔습니다. 수락하시겠습니까? (yes/no)"); string answer = System.Console.ReadLine(); FUP.Message rspMsg = new FUP.Message(); rspMsg.Body = new FUP.BodyResponse() { MSGID = reqMsg.Header.MSGID, RESPONSE = FUP.CONSTANTS.ACCEPTED }; rspMsg.Header = new FUP.Header() { MSGID = msgId++, MSGTYPE = FUP.CONSTANTS.REP_FILE_SEND, BODYLEN = (uint)rspMsg.Body.GetSize(), FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED, LASTMSG = FUP.CONSTANTS.LASTMSG, SEQ = 0 }; if (answer != "yes" && answer != "y") { rspMsg.Body = new FUP.BodyResponse() { MSGID = reqMsg.Header.MSGID, RESPONSE = FUP.CONSTANTS.DENIED }; FUP.MessageUtil.Send(stream, rspMsg); stream.Close(); client.Close(); continue; } else { FUP.MessageUtil.Send(stream, rspMsg); } System.Console.WriteLine("파일 전송을 시작합니다."); if (System.IO.Directory.Exists(dir) == false) { System.IO.Directory.CreateDirectory(dir); } long fileSize = reqBody.FILESIZE; string fileName = System.Text.Encoding.Default.GetString(reqBody.FILENAME); System.IO.FileStream file = new System.IO.FileStream(dir + "\\" + fileName, System.IO.FileMode.Create); uint? dataMsgId = null; ushort prevSeq = 0; while ((reqMsg = FUP.MessageUtil.Receive(stream)) != null) { System.Console.Write("#"); if (reqMsg.Header.MSGTYPE != FUP.CONSTANTS.FILE_SEND_DATA) { break; } if (dataMsgId == null) { dataMsgId = reqMsg.Header.MSGID; } else { if (dataMsgId != reqMsg.Header.MSGID) { break; } } if (prevSeq++ != reqMsg.Header.SEQ) { System.Console.WriteLine("{0}, {1}", prevSeq, reqMsg.Header.SEQ); break; } file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize()); if (reqMsg.Header.FRAGMENTED == FUP.CONSTANTS.NOT_FRAGMENTED) { break; } if (reqMsg.Header.LASTMSG == FUP.CONSTANTS.LASTMSG) { break; } } long recvFileSize = file.Length; file.Close(); System.Console.WriteLine(); System.Console.WriteLine("수신 파일 크기 : {0}byte", recvFileSize); FUP.Message rstMsg = new FUP.Message(); rstMsg.Body = new FUP.BodyResult() { MSGID = reqMsg.Header.MSGID, RESULT = FUP.CONSTANTS.SUCCESS }; rstMsg.Header = new FUP.Header() { MSGID = msgId++, MSGTYPE = FUP.CONSTANTS.FILE_SEND_RES, BODYLEN = (uint)rstMsg.Body.GetSize(), FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED, LASTMSG = FUP.CONSTANTS.LASTMSG, SEQ = 0 }; if (fileSize == recvFileSize) { FUP.MessageUtil.Send(stream, rstMsg); } else { rstMsg.Body = new FUP.BodyResult() { MSGID = reqMsg.Header.MSGID, RESULT = FUP.CONSTANTS.FAIL }; FUP.MessageUtil.Send(stream, rstMsg); } System.Console.WriteLine("파일 전송을 마쳤습니다."); stream.Close(); client.Close(); } } catch (System.Net.Sockets.SocketException e) { System.Console.WriteLine(e); } finally { server.Stop(); } } else if (args.Length == 2) { const int CHUNK_SIZE = 4096; string serverIp = args[0]; string filepath = args[1]; try { System.Net.IPEndPoint clientAddress = new System.Net.IPEndPoint(0, 0); System.Net.IPEndPoint serverAddress = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(serverIp), PORT); System.IO.FileInfo fileinfo = new System.IO.FileInfo(filepath); System.Console.WriteLine("클라이언트: {0}, 서버: {0}", clientAddress.ToString(), serverAddress.ToString()); uint msgId = 0; FUP.Message reqMsg = new FUP.Message(); reqMsg.Body = new FUP.BodyRequest() { FILESIZE = fileinfo.Length, FILENAME = System.Text.Encoding.Default.GetBytes(fileinfo.Name) }; reqMsg.Header = new FUP.Header() { MSGID = msgId++, MSGTYPE = FUP.CONSTANTS.REQ_FILE_SEND, BODYLEN = (uint)reqMsg.Body.GetSize(), FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED, LASTMSG = FUP.CONSTANTS.LASTMSG, SEQ = 0 }; System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(clientAddress); client.Connect(serverAddress); System.Net.Sockets.NetworkStream stream = client.GetStream(); FUP.MessageUtil.Send(stream, reqMsg); FUP.Message rspMsg = FUP.MessageUtil.Receive(stream); if (rspMsg.Header.MSGTYPE != FUP.CONSTANTS.REP_FILE_SEND) { System.Console.WriteLine("정상적인 서버 응답이 아닙니다. {0}", rspMsg.Header.MSGTYPE); return; } if (((FUP.BodyResponse)rspMsg.Body).RESPONSE == FUP.CONSTANTS.DENIED) { System.Console.WriteLine("서버에서 파일 전송을 거부했습니다."); return; } using (System.IO.Stream fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open)) { byte[] rbytes = new byte[CHUNK_SIZE]; long readValue = System.BitConverter.ToInt64(rbytes, 0); int totalRead = 0; ushort msgSeq = 0; byte fragmented = (fileStream.Length < CHUNK_SIZE) ? FUP.CONSTANTS.NOT_FRAGMENTED : FUP.CONSTANTS.FRAGMENTED; while (totalRead < fileStream.Length) { int read = fileStream.Read(rbytes, 0, CHUNK_SIZE); totalRead += read; FUP.Message fileMsg = new FUP.Message(); byte[] sendBytes = new byte[read]; System.Array.Copy(rbytes, 0, sendBytes, 0, read); fileMsg.Body = new FUP.BodyData(sendBytes); fileMsg.Header = new FUP.Header() { MSGID = msgId, MSGTYPE = FUP.CONSTANTS.FILE_SEND_DATA, BODYLEN = (uint)fileMsg.Body.GetSize(), FRAGMENTED = fragmented, LASTMSG = (totalRead < fileStream.Length) ? FUP.CONSTANTS.NOT_LASTMSG : FUP.CONSTANTS.LASTMSG, SEQ = msgSeq++ }; System.Console.Write("#"); FUP.MessageUtil.Send(stream, fileMsg); } System.Console.WriteLine(); FUP.Message rstMsg = FUP.MessageUtil.Receive(stream); FUP.BodyResult result = (FUP.BodyResult)rstMsg.Body; System.Console.WriteLine("파일 전송을 마쳤습니다."); } stream.Close(); client.Close(); } catch (System.Net.Sockets.SocketException e) { System.Console.WriteLine(e); } } else { System.Console.WriteLine("파일 받는 법:\t{0} \"다운로드 경로\"", System.Diagnostics.Process.GetCurrentProcess().ProcessName); System.Console.WriteLine("파일 보내는 법:\t{0} \"보낼 IP\" \"업로드할 파일\"", System.Diagnostics.Process.GetCurrentProcess().ProcessName); } return; }
/// <summary> Writes the mapping of the specified class in the specified hbm.xml file. </summary> /// <param name="filePath">Where the xml is written.</param> /// <param name="type">User-defined type containing a valid attribute (can be [Class] or [xSubclass]).</param> public virtual void Serialize(string filePath, System.Type type) { using (System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create)) Serialize(stream, type); }
/// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified hbm.xml file. </summary> /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param> /// <param name="filePath">Where the xml is written.</param> public virtual void Serialize(System.Reflection.Assembly assembly, string filePath) { using (System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create)) Serialize(stream, assembly); }
/// <summary> /// CSV to JSON conversion /// </summary> /// Convert a CSV file to a JSON object array /// <param name='inputFile'> /// Input file to perform the operation on. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <object> > CsvToJsonWithHttpMessagesAsync(System.IO.Stream inputFile, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (inputFile == null) { throw new ValidationException(ValidationRules.CannotBeNull, "inputFile"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("inputFile", inputFile); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CsvToJson", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "convert/csv/to/json").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; MultipartFormDataContent _multiPartContent = new MultipartFormDataContent(); if (inputFile != null) { StreamContent _inputFile = new StreamContent(inputFile); _inputFile.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); System.IO.FileStream _inputFileAsFileStream = inputFile as System.IO.FileStream; if (_inputFileAsFileStream != null) { ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "inputFile"; _contentDispositionHeaderValue.FileName = _inputFileAsFileStream.Name; _inputFile.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_inputFile, "inputFile"); } _httpRequest.Content = _multiPartContent; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <object>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
protected void Query(string request) { if (_queryInProgress) { throw new InvalidOperationException("Another query for this server is in progress"); } _queryInProgress = true; _readBuffer = new byte[100 * 1024]; // 100kb should be enought EndPoint _remoteEndPoint = (EndPoint)_remoteIpEndPoint; _packages = 0; int read = 0, bufferOffset = 0; // Request _sendBuffer = System.Text.Encoding.Default.GetBytes(request); _serverConnection.SendTo(_sendBuffer, _remoteIpEndPoint); // Response do { read = 0; try { // Multipackage check if (_packages > 0) { switch (_protocol) { case GameProtocol.HalfLife: case GameProtocol.Source: byte[] _tempBuffer = new byte[100 * 1024]; read = _serverConnection.ReceiveFrom(_tempBuffer, ref _remoteEndPoint); int packets = (_tempBuffer[8] & 15); int packetNr = (_tempBuffer[8] >> 4) + 1; if (packetNr < packets) { Array.Copy(_readBuffer, 9, _tempBuffer, read, bufferOffset); _readBuffer = _tempBuffer; } else { Array.Copy(_tempBuffer, 9, _readBuffer, bufferOffset, read); } _tempBuffer = null; break; case GameProtocol.GameSpy: case GameProtocol.GameSpy2: read = _serverConnection.ReceiveFrom(_readBuffer, bufferOffset, (_readBuffer.Length - bufferOffset), SocketFlags.None, ref _remoteEndPoint); break; default: case GameProtocol.Ase: case GameProtocol.Quake3: // these protocols don't support multi packages (i guess) break; } } // first package else { read = _serverConnection.ReceiveFrom(_readBuffer, ref _remoteEndPoint); } bufferOffset += read; _packages++; } catch (System.Net.Sockets.SocketException e) { #if DEBUG_QUERY System.Diagnostics.Trace.TraceError("Socket exception " + e.SocketErrorCode + " " + e.Message); #endif break; } } while (read > 0); _scanTime = DateTime.Now; if (bufferOffset > 0 && bufferOffset < _readBuffer.Length) { byte[] temp = new byte[bufferOffset]; for (int i = 0; i < temp.Length; i++) { temp[i] = _readBuffer[i]; } _readBuffer = temp; temp = null; } else { #if DEBUG_QUERY System.Diagnostics.Trace.TraceError("Answer is either zero-length or exceeds buffer length"); #endif _isOnline = false; } _responseString = System.Text.Encoding.Default.GetString(_readBuffer); _queryInProgress = false; if (_debugMode) { System.IO.FileStream stream = System.IO.File.OpenWrite(".dat"); stream.Write(_readBuffer, 0, _readBuffer.Length); stream.Close(); } }
public void Get(string remotename, string filename) { using (System.IO.FileStream fs = System.IO.File.Create(filename)) Get(remotename, fs); }
public void Put(string remotename, string filename) { using (System.IO.FileStream fs = System.IO.File.OpenRead(filename)) Put(remotename, fs); }
public void Put(string remotename, string localname) { using (System.IO.FileStream fs = System.IO.File.Open(localname, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) Put(remotename, fs); }
public System.Drawing.Imaging.Metafile ToMetaFile_(string html, double width, double height, double marginL, double marginT, double marginR, double marginB) { double w = width - marginL - marginR; double h = height - marginT - marginB; string pageSizeStyle = string.Format("width: {0}mm;height: {1}mm;margin-left: 0px;margin-right: 0px;", w, h); wb.Document.OpenNew(false); wb.Document.Write(html); wb.Refresh(); wb.Document.Body.Style = pageSizeStyle; wb.Refresh(); wb.Width = wb.Document.Body.ScrollRectangle.Width; wb.Height = wb.Document.Body.ScrollRectangle.Height; System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (var graHandle = System.Drawing.Graphics.FromHwnd(IntPtr.Zero)) { double dpix = graHandle.DpiX; double dpiy = graHandle.DpiY; var hdc = graHandle.GetHdc(); System.Drawing.Imaging.Metafile meta = new System.Drawing.Imaging.Metafile(ms, hdc, new System.Drawing.RectangleF(0, 0, (float)w, (float)h), System.Drawing.Imaging.MetafileFrameUnit.Millimeter); using (var g = Graphics.FromImage(meta)) { } double hres = meta.HorizontalResolution; double vres = meta.VerticalResolution; meta = new System.Drawing.Imaging.Metafile(ms, hdc, new System.Drawing.RectangleF(0, 0, (float)w, (float)h), System.Drawing.Imaging.MetafileFrameUnit.Millimeter); using (var g = Graphics.FromImage(meta)) { double scale = hres / 25.4; RECT r = new RECT(); r.Left = 0; r.Top = 0; r.Right = (int)w; r.Bottom = (int)((double)w * (double)wb.Document.Body.ScrollRectangle.Height / (double)wb.Document.Body.ScrollRectangle.Width); r.Right *= 10; //g.PageUnit = GraphicsUnit.Millimeter; try { var hdc2 = g.GetHdc(); try { var unknown = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(wb.ActiveXInstance); try { OleDraw(unknown, (int)System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT, hdc2, ref r); } finally { System.Runtime.InteropServices.Marshal.Release(unknown); } } finally { g.ReleaseHdc(hdc2); } for (int x = 0; x <= width; x += 10) { g.DrawLine(System.Drawing.Pens.Red, new System.Drawing.Point(x, 0), new System.Drawing.Point(x, 297)); } } finally { graHandle.ReleaseHdc(hdc); } } meta.Dispose(); } ms.Position = 0; using (System.IO.FileStream fs = System.IO.File.OpenWrite("j:\\test.emf")) { ms.WriteTo(fs); } ms.Position = 0; return(System.Drawing.Imaging.Metafile.FromStream(ms) as System.Drawing.Imaging.Metafile); }
public void Get(string remotename, string localname) { using (System.IO.FileStream fs = System.IO.File.Open(localname, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) Get(remotename, fs); }
public static void unzipFile(string inputZip, string destinationDirectory) { int buffer = 2048; List <string> zipFiles = new List <string>(); File sourceZipFile = new File(inputZip); File unzipDirectory = new File(destinationDirectory); createDir(unzipDirectory.AbsolutePath); ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OpenRead); IEnumeration zipFileEntries = zipFile.Entries(); while (zipFileEntries.HasMoreElements) { ZipEntry entry = (ZipEntry)zipFileEntries.NextElement(); string currentEntry = entry.Name; File destFile = new File(unzipDirectory, currentEntry); if (currentEntry.EndsWith(Constant.SUFFIX_ZIP)) { zipFiles.Add(destFile.AbsolutePath); } File destinationParent = destFile.ParentFile; createDir(destinationParent.AbsolutePath); if (!entry.IsDirectory) { if (destFile != null && destFile.Exists()) { LogUtils.i(destFile + "已存在"); continue; } BufferedInputStream inputStream = new BufferedInputStream(zipFile.GetInputStream(entry)); int currentByte; // buffer for writing file byte[] data = new byte[buffer]; var fos = new System.IO.FileStream(destFile.AbsolutePath, System.IO.FileMode.OpenOrCreate); BufferedOutputStream dest = new BufferedOutputStream(fos, buffer); while ((currentByte = inputStream.Read(data, 0, buffer)) != -1) { dest.Write(data, 0, currentByte); } dest.Flush(); dest.Close(); inputStream.Close(); } } zipFile.Close(); foreach (var zipName in zipFiles) { unzipFile(zipName, destinationDirectory + File.SeparatorChar + zipName.Substring(0, zipName.LastIndexOf(Constant.SUFFIX_ZIP))); } }
/// <summary>Renames an existing file in the directory. </summary> public override void RenameFile(System.String from, System.String to) { lock (this) { System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from)); System.IO.FileInfo nu = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, to)); /* This is not atomic. If the program crashes between the call to * delete() and the call to renameTo() then we're screwed, but I've * been unable to figure out how else to do this... */ bool tmpBool; if (System.IO.File.Exists(nu.FullName)) { tmpBool = true; } else { tmpBool = System.IO.Directory.Exists(nu.FullName); } if (tmpBool) { bool tmpBool2; if (System.IO.File.Exists(nu.FullName)) { System.IO.File.Delete(nu.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(nu.FullName)) { System.IO.Directory.Delete(nu.FullName); tmpBool2 = true; } else { tmpBool2 = false; } if (!tmpBool2) { throw new System.IO.IOException("Cannot delete " + nu); } } // Rename the old file to the new one. Unfortunately, the renameTo() // method does not work reliably under some JVMs. Therefore, if the // rename fails, we manually rename by copying the old file to the new one try { old.MoveTo(nu.FullName); } catch (System.Exception) { System.IO.Stream in_Renamed = null; System.IO.Stream out_Renamed = null; try { in_Renamed = new System.IO.FileStream(old.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read); out_Renamed = new System.IO.FileStream(nu.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); // see if the buffer needs to be initialized. Initialization is // only done on-demand since many VM's will never run into the renameTo // bug and hence shouldn't waste 1K of mem for no reason. if (buffer == null) { buffer = new byte[1024]; } int len; while ((len = in_Renamed.Read(buffer, 0, buffer.Length)) > 0) { out_Renamed.Write(buffer, 0, len); } // delete the old file. bool tmpBool3; if (System.IO.File.Exists(old.FullName)) { System.IO.File.Delete(old.FullName); tmpBool3 = true; } else if (System.IO.Directory.Exists(old.FullName)) { System.IO.Directory.Delete(old.FullName); tmpBool3 = true; } else { tmpBool3 = false; } bool generatedAux = tmpBool3; } catch (System.IO.IOException ioe) { throw new System.IO.IOException("Cannot rename " + old + " to " + nu); } finally { if (in_Renamed != null) { try { in_Renamed.Close(); } catch (System.IO.IOException e) { throw new System.SystemException("Cannot close input stream: " + e.ToString()); } } if (out_Renamed != null) { try { out_Renamed.Close(); } catch (System.IO.IOException e) { throw new System.SystemException("Cannot close output stream: " + e.ToString()); } } } } } }
// LoadMessageResource() // - Load Message Data // Return Value // - Boolean : Return True/False // Arguments // - // public static bool LoadMessageResource() { System.IO.FileStream fs = null; System.Xml.XmlTextReader xtr = null; string[] sTemp = new string[3]; int i; int j; GlobalVariable.gsMessageData = new string[3, GlobalVariable.giMaxMessageData]; j = 1; try { // Open XML File if (Microsoft.VisualBasic.FileSystem.Dir(modGlobalConstant.MP_MESSAGE_FILE, 0) == "") { return(true); } fs = new System.IO.FileStream(modGlobalConstant.MP_MESSAGE_FILE, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); // Set xmlReader xtr = new XmlTextReader(fs); while (xtr.Read()) { switch (xtr.NodeType) { case XmlNodeType.Element: switch (xtr.Name.ToUpper()) { case "TEXT": xtr.MoveToAttribute("Key"); j = CmnFunction.ToInt(xtr.Value); i = 0; while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Text) { sTemp[i] = xtr.Value.Trim(); i++; } else if (xtr.NodeType == XmlNodeType.EndElement && xtr.Name.ToUpper() == "TEXT") { break; } } GlobalVariable.gsMessageData[0, j] = sTemp[0]; GlobalVariable.gsMessageData[1, j] = sTemp[1]; GlobalVariable.gsMessageData[2, j] = sTemp[2]; break; } break; } } } catch (Exception) { if (!(xtr == null)) { CmnFunction.ShowMsgBox("Occured error in read language file." + "\r\n" + "\r\n" + "\'" + xtr.Name + xtr.Value + "\'", "FMB Client", MessageBoxButtons.OK, 1); } } finally { // Close XML File if (!(xtr == null)) { xtr.Close(); } if (!(fs == null)) { fs.Close(); } } return(true); }
public static void Main(System.String[] args) { if (args.Length < 2) { ExitWithUsage(); } System.Type stemClass = System.Type.GetType("SF.Snowball.Ext." + args[0] + "Stemmer"); SnowballProgram stemmer = (SnowballProgram)System.Activator.CreateInstance(stemClass); System.Reflection.MethodInfo stemMethod = stemClass.GetMethod("stem", (new System.Type[0] == null)?new System.Type[0]:(System.Type[]) new System.Type[0]); System.IO.StreamReader reader; reader = new System.IO.StreamReader(new System.IO.FileStream(args[1], System.IO.FileMode.Open, System.IO.FileAccess.Read), System.Text.Encoding.Default); reader = new System.IO.StreamReader(reader.BaseStream, reader.CurrentEncoding); System.Text.StringBuilder input = new System.Text.StringBuilder(); System.IO.Stream outstream = System.Console.OpenStandardOutput(); if (args.Length > 2 && args[2].Equals("-o")) { outstream = new System.IO.FileStream(args[3], System.IO.FileMode.Create); } else if (args.Length > 2) { ExitWithUsage(); } System.IO.StreamWriter output = new System.IO.StreamWriter(outstream, System.Text.Encoding.Default); output = new System.IO.StreamWriter(output.BaseStream, output.Encoding); int repeat = 1; if (args.Length > 4) { repeat = System.Int32.Parse(args[4]); } System.Object[] emptyArgs = new System.Object[0]; int character; while ((character = reader.Read()) != -1) { char ch = (char)character; if (System.Char.IsWhiteSpace(ch)) { if (input.Length > 0) { stemmer.SetCurrent(input.ToString()); for (int i = repeat; i != 0; i--) { stemMethod.Invoke(stemmer, (System.Object[])emptyArgs); } output.Write(stemmer.GetCurrent()); output.Write('\n'); input.Remove(0, input.Length - 0); } } else { input.Append(System.Char.ToLower(ch)); } } output.Flush(); }
public static void SetAccessControl(this System.IO.FileStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity) { }
public static bool LoadCaptionResource() { const int MENU_TYPE = 0; const int BUTTON_TYPE = 1; const int OTHER_TYPE = 2; System.IO.FileStream fs = null; System.Xml.XmlTextReader xtr = null; GlobalVariable.gLanguageData lang; int iCapType = 0; string[] sTemp = new string[3]; int i; CaptionLangSort langSort; try { GlobalVariable.gaButtonLanguage.Clear(); GlobalVariable.gaMenuLanguage.Clear(); GlobalVariable.gaTextLanguage.Clear(); // Open XML File if (Microsoft.VisualBasic.FileSystem.Dir(modGlobalConstant.MP_CAPTION_FILE, 0) == "") { return(true); } fs = new System.IO.FileStream(modGlobalConstant.MP_CAPTION_FILE, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); // Set xmlReader xtr = new XmlTextReader(fs); while (xtr.Read()) { switch (xtr.NodeType) { case XmlNodeType.Element: switch (xtr.Name.ToUpper()) { case "BUTTON": iCapType = BUTTON_TYPE; break; case "MENU": iCapType = MENU_TYPE; break; case "OTHER": iCapType = OTHER_TYPE; break; case "TEXT": xtr.MoveToAttribute("Key"); lang.Key = xtr.Value.ToUpper(); i = 0; while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Text) { sTemp[i] = xtr.Value; i++; } else if (xtr.NodeType == XmlNodeType.EndElement && xtr.Name.ToUpper() == "TEXT") { break; } } lang.Lang_1 = sTemp[0]; lang.Lang_2 = sTemp[1]; lang.Lang_3 = sTemp[2]; switch (iCapType) { case BUTTON_TYPE: GlobalVariable.gaButtonLanguage.Add(lang); break; case MENU_TYPE: GlobalVariable.gaMenuLanguage.Add(lang); break; case OTHER_TYPE: GlobalVariable.gaTextLanguage.Add(lang); break; } break; } break; } } langSort = new CaptionLangSort(); GlobalVariable.gaButtonLanguage.Sort(langSort); GlobalVariable.gaMenuLanguage.Sort(langSort); GlobalVariable.gaTextLanguage.Sort(langSort); } catch (Exception) { if (!(xtr == null)) { CmnFunction.ShowMsgBox("Occured error in read language file." + "\r\n" + "\r\n" + "\'" + xtr.Name + xtr.Value + "\'", "FMB Client", MessageBoxButtons.OK, 1); } } finally { // Close XML File if (!(xtr == null)) { xtr.Close(); } if (!(fs == null)) { fs.Close(); } } return(true); }
private void OpenFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { TStreamFormat format = player.GetFileFormat(OpenFileDialog1.FileName); if (LoadMode == 0) { player.Close(); if (! (player.OpenFile(OpenFileDialog1.FileName, TStreamFormat.sfAutodetect ))) { MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else if (LoadMode == 1) { player.Close(); System.IO.FileInfo fInfo = new System.IO.FileInfo(OpenFileDialog1.FileName); long numBytes = fInfo.Length; System.IO.FileStream fStream = new System.IO.FileStream(OpenFileDialog1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fStream); byte[] stream_data = null; stream_data = br.ReadBytes(System.Convert.ToInt32((int)(numBytes))); if (!(player.OpenStream(true, false, ref stream_data, System.Convert.ToUInt32(numBytes), format))) { MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error); } br.Close(); fStream.Close(); } else if (LoadMode == 2) { player.Close(); BufferCounter = 0; System.IO.FileInfo fInfo = new System.IO.FileInfo(OpenFileDialog1.FileName); uint numBytes = System.Convert.ToUInt32(fInfo.Length); if (br != null) { br.Close(); } if (fStream != null) { fStream.Close(); } br = null; fStream = null; fStream = new System.IO.FileStream(OpenFileDialog1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); br = new System.IO.BinaryReader(fStream); byte[] stream_data = null; uint small_chunk = 0; small_chunk = System.Convert.ToUInt32(Math.Min(100000, numBytes)); // read small chunk of data stream_data = br.ReadBytes(System.Convert.ToInt32((int)(small_chunk))); // open stream if (! (player.OpenStream(true, true, ref stream_data, System.Convert.ToUInt32(stream_data.Length), format))) { MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error); } // read more data and push into stream stream_data = br.ReadBytes(System.Convert.ToInt32((int)(small_chunk))); player.PushDataToStream(ref stream_data, System.Convert.ToUInt32(stream_data.Length)); } else if (LoadMode == 3) { if (!(player.AddFile(OpenFileDialog1.FileName, TStreamFormat.sfAutodetect))) { MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } showinfo(); player.StartPlayback(); }
public Task PutAsync(string remotename, string filename, CancellationToken cancelToken) { using (System.IO.FileStream fs = System.IO.File.OpenRead(filename)) return(PutAsync(remotename, fs, cancelToken)); }
/// <summary> /// Serialize the whole UI to filename. /// Note: serialization have some limitation and things that will not be included in xml, /// like even handlers. Please read docs carefuly to know what to expect. /// </summary> /// <param name="path">Filename to serialize into.</param> public void Serialize(string path) { System.IO.FileStream file = System.IO.File.Create(path); Serialize(file); file.Dispose(); }
public static System.Security.AccessControl.FileSecurity GetAccessControl(this System.IO.FileStream fileStream) { throw null; }
private void HttpGetProc(UrlItem url, string filename) { if (url == null) { vm_.addLog("error, No URL selected."); return; } vm_.addLog("request, " + url.Name_ + ", " + url.Path_); // MessageBox.Show(url.Name_ + "\n" + url.Path_); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url.Path_); req.Credentials = new System.Net.NetworkCredential(url.Username_, url.Password_); // あってもなくても System.Net.HttpWebResponse res = null; try { res = (System.Net.HttpWebResponse)req.GetResponse(); System.IO.Stream st = res.GetResponseStream(); System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write); byte[] buf = new byte[1024]; while (true) { int readsize = st.Read(buf, 0, buf.Length); if (readsize == 0) { break; } fs.Write(buf, 0, readsize); } fs.Close(); st.Close(); vm_.addLog("done"); } catch (System.IO.IOException ex) { vm_.addLog("error, " + ex.Message); } catch (System.Net.WebException ex) { if (ex.Status == System.Net.WebExceptionStatus.ProtocolError) { System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse)ex.Response; //MessageBox.Show(errres.ResponseUri + "\n" + errres.StatusCode + "\n" + errres.StatusDescription); vm_.addLog("error, " + errres.ResponseUri); vm_.addLog("error, " + errres.StatusCode); vm_.addLog("error, " + errres.StatusDescription); } else { //MessageBox.Show(ex.Message); vm_.addLog("error, " + ex.Message); } } catch (Exception ex) { vm_.addLog("error, " + ex.Message); } finally { if (res != null) { res.Close(); } } }
/// <summary> /// Deserialize the whole UI from filename. /// Note: serialization have some limitation and things that will not be included in xml, /// like even handlers. Please read docs carefuly to know what to expect. /// </summary> /// <param name="path">Filename to deserialize from.</param> public void Deserialize(string path) { System.IO.FileStream file = System.IO.File.OpenRead(path); Deserialize(file); file.Dispose(); }
public void GetFileObject(string bucketName, string keyName, string localfile) { using (System.IO.FileStream fs = System.IO.File.Open(localfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) GetFileStream(bucketName, keyName, fs); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null)) { if (data.Data != null) { Android.Net.Uri uri = data.Data; filePath = CommonHelper.GetRealPathFromURI(this, data.Data); int height = 200; int width = 200; BitmapHelper._file = new File(filePath); Picasso.With(this).Load(BitmapHelper._file) .Transform(new CircleTransformation()) .CenterCrop() .Resize(200, 150).Into(profileChange); BitmapHelper.bitmap = BitmapHelper._file.Path.LoadAndResizeBitmap(width, height); try { using (var os = new System.IO.FileStream(BitmapHelper._dir + String.Format("myProfile_{0}.jpg", Guid.NewGuid()), System.IO.FileMode.CreateNew)) { BitmapHelper.bitmap.Compress(Bitmap.CompressFormat.Jpeg, 95, os); filePath = os.Name; } } catch (Exception e) { Toast.MakeText(this, e.Message, ToastLength.Long).Show(); } mediaType = "Photo"; } } if ((requestCode == CAMERA_REQUEST)) { if (BitmapHelper._file.AbsolutePath != null) { Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); Android.Net.Uri contentUri = Android.Net.Uri.FromFile(BitmapHelper._file); mediaScanIntent.SetData(contentUri); // profileChange.SetImageURI(contentUri); int height = 200; int width = 200; Picasso.With(this).Load(contentUri) .Transform(new CircleTransformation()) .CenterCrop() .Resize(200, 150).Into(profileChange); BitmapHelper.bitmap = BitmapHelper._file.Path.LoadAndResizeBitmap(width, height); try { using (var os = new System.IO.FileStream(BitmapHelper._dir + String.Format("myProfile_{0}.jpg", Guid.NewGuid()), System.IO.FileMode.CreateNew)) { BitmapHelper.bitmap.Compress(Bitmap.CompressFormat.Jpeg, 95, os); filePath = os.Name; } } catch (Exception e) { Toast.MakeText(this, e.Message, ToastLength.Long).Show(); } mediaType = "Photo"; } } }
private void imprimiPDF() { try { //Cria a iTextSharp Table da DataTable iTextSharp.text.pdf.PdfPTable pdfTable = new iTextSharp.text.pdf.PdfPTable(dgvConsulta.ColumnCount); pdfTable.DefaultCell.Padding = 0; pdfTable.DefaultCell.PaddingBottom = 5; pdfTable.DefaultCell.PaddingTop = 5; pdfTable.WidthPercentage = 100; pdfTable.DefaultCell.BorderWidth = 0; pdfTable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; var font = iTextSharp.text.FontFactory.GetFont("Arial", 8.5f); pdfTable.DefaultCell.Phrase = new iTextSharp.text.Phrase() { Font = font }; //Adiciona a linha do cabeçalho foreach (DataGridViewColumn column in dgvConsulta.Columns) { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell.BorderWidth = 0; pdfTable.AddCell(new iTextSharp.text.Phrase(column.HeaderText.ToString(), font)); //pdfTable.AddCell(cell); //pdfTable.AddCell(new Phrase(cell.ToString(), font)); } //Adiciona as linhas foreach (DataGridViewRow row in dgvConsulta.Rows) { foreach (DataGridViewCell cell in row.Cells) { pdfTable.AddCell(new iTextSharp.text.Phrase(cell.Value.ToString(), font)); } } //Exporta para PDF string folderPath = @"\\10.0.3.35\d\Debug\report\RELATÓRIO DE " + frmMenu.lbTitulo.Text + ".pdf"; using (System.IO.FileStream stream = new System.IO.FileStream(folderPath, System.IO.FileMode.Create)) { //Configurando e adicionando os paragrafos iTextSharp.text.Paragraph ph1 = new iTextSharp.text.Paragraph("RELATÓRIO DE " + frmMenu.lbTitulo.Text); ph1.Alignment = iTextSharp.text.Element.ALIGN_CENTER; ph1.Font.SetStyle(5); iTextSharp.text.Paragraph ph2 = new iTextSharp.text.Paragraph(lbDeveloped.Text); //ph2.Alignment = iTextSharp.text.Element.ALIGN_CENTER; iTextSharp.text.Paragraph ph3 = new iTextSharp.text.Paragraph(lbRaf.Text); //ph3.Alignment = iTextSharp.text.Element.ALIGN_CENTER; ph3.Font.SetStyle(1); // 1 - negrito; iTextSharp.text.Paragraph ph4 = new iTextSharp.text.Paragraph(lLemail.Text); //ph4.Alignment = iTextSharp.text.Element.ALIGN_CENTER; iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10); iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(@"\\10.0.3.35\d\Debug\image\logo_nova.JPG"); logo.ScalePercent(0.3f * 100); logo.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDoc.Add(logo); pdfDoc.Add(ph1); //pdfDoc.Add(new iTextSharp.text.Paragraph(" ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); pdfDoc.Add(new iTextSharp.text.Paragraph("Período.......: " + txtInicio.Text + " à " + txtFim.Text)); pdfDoc.Add(new iTextSharp.text.Paragraph("Usuário.......: " + frmMenu.lbNome.Text)); pdfDoc.Add(new iTextSharp.text.Paragraph("Emitido em.: " + DateTime.Now.ToString())); pdfDoc.Add(ph2); pdfDoc.Add(ph3); pdfDoc.Add(ph4); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); System.Diagnostics.Process.Start(folderPath); // iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); // string caminho = Application.StartupPath + @"\Exemplo.pdf"; // iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new System.IO.FileStream(caminho, System.IO.FileMode.Create)); // try // { // doc.SetMargins(30, 30, 70, 70); // doc.AddCreationDate(); // doc.Open(); // iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(brocaFornecedor().ToString()); // par.Alignment = iTextSharp.text.Element.ALIGN_JUSTIFIED; // par.Add("Teste na criação de um arquivo PDF"); // doc.Add(par); // doc.Close(); // System.Diagnostics.Process.Start(caminho); // } // catch (Exception Ex) // { // MessageBox.Show("Ocorreu um erro ao gerar o PDF - Erro:", Ex.Message); // } //} } } catch (Exception ex) { MessageBox.Show("OPSS.. OCORREU UM ERRO! " + ex.Message); } }
public void AddFileObject(string bucketName, string keyName, string localfile) { using (System.IO.FileStream fs = System.IO.File.Open(localfile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) AddFileStream(bucketName, keyName, fs); }
/// <summary> /// /// </summary> /// <param name="serverName"></param> /// <param name="path"></param> /// <param name="messaggio"></param> /// <param name="infoUtente"></param> /// <param name="ruolo"></param> /// <param name="registro"></param> /// <param name="destinatario"></param> private static void processaMessaggio(string serverName, string path, ZfLib.Message messaggio, DocsPaVO.utente.InfoUtente infoUtente, DocsPaVO.utente.Ruolo ruolo, DocsPaVO.utente.Registro registro, DocsPaVO.utente.Corrispondente destinatario) { logger.Debug("processaMessaggio"); System.IO.FileStream fs = null; bool daAggiornareUffRef = false; bool dbOpen = false; bool fsOpen = false; try { //informazioni sul fax string dataRic = messaggio.GetMsgHistories()[0].Date.ToString(); logger.Debug(" @ dataric = " + dataRic); //accesso al file del fax fs = getFileStream(path + messaggio.GetMsgInfo().Body); //=new System.IO.FileStream(path+messaggio.GetMsgInfo().Body+".G3N",System.IO.FileMode.Open,System.IO.FileAccess.ReadWrite,System.IO.FileShare.ReadWrite); logger.Debug(fs.CanRead.ToString() + "@ OK @"); fsOpen = true; //creazione scheda documento DocsPaVO.documento.SchedaDocumento sd = new DocsPaVO.documento.SchedaDocumento(); sd.idPeople = infoUtente.idPeople; logger.Debug("sd.idPeople = " + sd.idPeople.ToString()); sd.userId = infoUtente.userId; logger.Debug("sd.userId = " + sd.userId.ToString()); DocsPaVO.documento.Oggetto ogg = new DocsPaVO.documento.Oggetto(); ogg.descrizione = "Fax ricevuto in data " + dataRic; //DA COMPLETARE sd.oggetto = ogg; sd.predisponiProtocollazione = true; sd.registro = registro; sd.tipoProto = "A"; sd.typeId = "MAIL"; //aggiunta protocollo entrata DocsPaVO.documento.ProtocolloEntrata protEntr = new DocsPaVO.documento.ProtocolloEntrata(); DocsPaVO.utente.Corrispondente mittente = new DocsPaVO.utente.Corrispondente(); mittente.descrizione = messaggio.GetMsgInfo().Comment; logger.Debug(" @ mittente.descrizione = " + mittente.descrizione); //"QUI SI METTONO INFORMAZIONI"; protEntr.mittente = mittente; sd.protocollo = protEntr; protEntr.dataProtocollazione = System.DateTime.Today.ToString(); sd.appId = "ACROBAT"; sd = BusinessLogic.Documenti.DocSave.addDocGrigia(sd, infoUtente, ruolo); logger.Debug("Salvataggio doc..."); sd = BusinessLogic.Documenti.DocSave.save(infoUtente, sd, false, out daAggiornareUffRef, ruolo); logger.Debug("Salvataggio eseguito"); DocsPaVO.documento.FileDocumento fd = new DocsPaVO.documento.FileDocumento(); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); fd.content = buffer; fd.length = buffer.Length; fd.name = "fax.tif"; BusinessLogic.Documenti.FileManager.putFile((DocsPaVO.documento.FileRequest)sd.documenti[0], fd, infoUtente); logger.Debug("Documento inserito"); fs.Close(); fsOpen = false; //TRASMISSIONE DocsPaVO.trasmissione.Trasmissione trasm = new DocsPaVO.trasmissione.Trasmissione(); trasm.ruolo = ruolo; //db.openConnection(); dbOpen = true; trasm.utente = BusinessLogic.Utenti.UserManager.getUtente(infoUtente.idPeople); DocsPaVO.documento.InfoDocumento infoDoc = new DocsPaVO.documento.InfoDocumento(); infoDoc.idProfile = sd.systemId; infoDoc.docNumber = sd.docNumber; infoDoc.oggetto = sd.oggetto.descrizione; infoDoc.tipoProto = "A"; trasm.infoDocumento = infoDoc; //costruzione singole trasmissioni DocsPaVO.trasmissione.RagioneTrasmissione ragione = getRagioneTrasm(); System.Collections.ArrayList dest = new System.Collections.ArrayList(); dest.Add(destinatario); System.Collections.ArrayList trasmissioniSing = new System.Collections.ArrayList(); for (int i = 0; i < dest.Count; i++) { DocsPaVO.trasmissione.TrasmissioneSingola trSing = new DocsPaVO.trasmissione.TrasmissioneSingola(); trSing.ragione = ragione; logger.Debug(dest[i].GetType().ToString()); if (dest[i].GetType().Equals(typeof(DocsPaVO.utente.Ruolo))) { logger.Debug("ruolo"); trSing.corrispondenteInterno = (DocsPaVO.utente.Ruolo)dest[i]; } else { logger.Debug("utente"); trSing.corrispondenteInterno = (DocsPaVO.utente.Utente)dest[i]; } logger.Debug("ok"); trSing.tipoTrasm = "S"; if (dest[i].GetType().Equals(typeof(DocsPaVO.utente.Ruolo))) { logger.Debug("caso ruolo"); trSing.tipoDest = DocsPaVO.trasmissione.TipoDestinatario.RUOLO; //ricerca degli utenti del ruolo System.Collections.ArrayList utenti = new System.Collections.ArrayList(); DocsPaVO.addressbook.QueryCorrispondente qc = new DocsPaVO.addressbook.QueryCorrispondente(); qc.codiceRubrica = ((DocsPaVO.utente.Ruolo)dest[i]).codiceRubrica; System.Collections.ArrayList registri = new System.Collections.ArrayList(); registri.Add(registro.systemId); qc.idRegistri = registri; qc.idAmministrazione = registro.idAmministrazione; qc.getChildren = true; utenti = BusinessLogic.Utenti.addressBookManager.listaCorrispondentiIntMethod(qc); System.Collections.ArrayList trasmissioniUt = new System.Collections.ArrayList(); for (int k = 0; k < utenti.Count; k++) { DocsPaVO.trasmissione.TrasmissioneUtente trUt = new DocsPaVO.trasmissione.TrasmissioneUtente(); trUt.utente = (DocsPaVO.utente.Utente)utenti[k]; trasmissioniUt.Add(trUt); } trSing.trasmissioneUtente = trasmissioniUt; } else { logger.Debug("Caso utente"); trSing.tipoDest = DocsPaVO.trasmissione.TipoDestinatario.UTENTE; System.Collections.ArrayList trasmissioniUt = new System.Collections.ArrayList(); DocsPaVO.trasmissione.TrasmissioneUtente trUt = new DocsPaVO.trasmissione.TrasmissioneUtente(); trUt.utente = (DocsPaVO.utente.Utente)dest[i]; trasmissioniUt.Add(trUt); trSing.trasmissioneUtente = trasmissioniUt; } trasmissioniSing.Add(trSing); } trasm.trasmissioniSingole = trasmissioniSing; if (infoUtente.delegato != null) { trasm.delegato = ((DocsPaVO.utente.InfoUtente)(infoUtente.delegato)).idPeople; } //BusinessLogic.Trasmissioni.TrasmManager.saveTrasmMethod(trasm); //BusinessLogic.Trasmissioni.ExecTrasmManager.executeTrasmMethod(serverName,trasm); BusinessLogic.Trasmissioni.ExecTrasmManager.saveExecuteTrasmMethod(serverName, trasm); } catch (Exception e) { logger.Debug(e.Message); if (fsOpen) { fs.Close(); } if (dbOpen) { //db.closeConnection(); } logger.Debug("Errore nella gestione dei fax (processaMessaggio)", e); throw e; } }
private IEnumerable <IFileEntry> ListWithouExceptionCatch() { var req = CreateRequest(""); req.Method = "PROPFIND"; req.Headers.Add("Depth", "1"); req.ContentType = "text/xml"; req.ContentLength = PROPFIND_BODY.Length; var areq = new Utility.AsyncHttpRequest(req); using (System.IO.Stream s = areq.GetRequestStream()) s.Write(PROPFIND_BODY, 0, PROPFIND_BODY.Length); var doc = new System.Xml.XmlDocument(); using (var resp = (System.Net.HttpWebResponse)areq.GetResponse()) { int code = (int)resp.StatusCode; if (code < 200 || code >= 300) //For some reason Mono does not throw this automatically { throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp); } if (!string.IsNullOrEmpty(m_debugPropfindFile)) { using (var rs = areq.GetResponseStream()) using (var fs = new System.IO.FileStream(m_debugPropfindFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) Utility.Utility.CopyStream(rs, fs, false, m_copybuffer); doc.Load(m_debugPropfindFile); } else { using (var rs = areq.GetResponseStream()) doc.Load(rs); } } System.Xml.XmlNamespaceManager nm = new System.Xml.XmlNamespaceManager(doc.NameTable); nm.AddNamespace("D", "DAV:"); List <IFileEntry> files = new List <IFileEntry>(); m_filenamelist = new List <string>(); foreach (System.Xml.XmlNode n in doc.SelectNodes("D:multistatus/D:response/D:href", nm)) { //IIS uses %20 for spaces and %2B for + //Apache uses %20 for spaces and + for + string name = Library.Utility.Uri.UrlDecode(n.InnerText.Replace("+", "%2B")); string cmp_path; //TODO: This list is getting ridiculous, should change to regexps if (name.StartsWith(m_url, StringComparison.Ordinal)) { cmp_path = m_url; } else if (name.StartsWith(m_rawurl, StringComparison.Ordinal)) { cmp_path = m_rawurl; } else if (name.StartsWith(m_rawurlPort, StringComparison.Ordinal)) { cmp_path = m_rawurlPort; } else if (name.StartsWith(m_path, StringComparison.Ordinal)) { cmp_path = m_path; } else if (name.StartsWith("/" + m_path, StringComparison.Ordinal)) { cmp_path = "/" + m_path; } else if (name.StartsWith(m_sanitizedUrl, StringComparison.Ordinal)) { cmp_path = m_sanitizedUrl; } else if (name.StartsWith(m_reverseProtocolUrl, StringComparison.Ordinal)) { cmp_path = m_reverseProtocolUrl; } else { continue; } if (name.Length <= cmp_path.Length) { continue; } name = name.Substring(cmp_path.Length); long size = -1; DateTime lastAccess = new DateTime(); DateTime lastModified = new DateTime(); bool isCollection = false; System.Xml.XmlNode stat = n.ParentNode.SelectSingleNode("D:propstat/D:prop", nm); if (stat != null) { System.Xml.XmlNode s = stat.SelectSingleNode("D:getcontentlength", nm); if (s != null) { size = long.Parse(s.InnerText); } s = stat.SelectSingleNode("D:getlastmodified", nm); if (s != null) { try { //Not important if this succeeds lastAccess = lastModified = DateTime.Parse(s.InnerText, System.Globalization.CultureInfo.InvariantCulture); } catch { } } s = stat.SelectSingleNode("D:iscollection", nm); if (s != null) { isCollection = s.InnerText.Trim() == "1"; } else { isCollection = (stat.SelectSingleNode("D:resourcetype/D:collection", nm) != null); } } FileEntry fe = new FileEntry(name, size, lastAccess, lastModified); fe.IsFolder = isCollection; files.Add(fe); m_filenamelist.Add(name); } return(files); }
private List <WorkName> ExcelToDataTable(string filename) { List <WorkName> list = new List <WorkName>(); IWorkbook book; var exten = System.IO.Path.GetExtension(filename); if (!exten.ToLower().Equals(".xls") && !exten.ToLower().Equals(".xlsx")) { //不是excel文件,返回提示 return(null); } using (System.IO.Stream rem = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { //1、读取excel (版本不一样) if (exten.ToLower().Equals(".xls")) { book = new NPOI.HSSF.UserModel.HSSFWorkbook(rem); } else { book = new NPOI.XSSF.UserModel.XSSFWorkbook(rem); } var sheet = book.GetSheetAt(0); int rows = sheet.ActiveCell.Row; //数据行 for (int r = 0; r < rows; r++) { WorkName work = new WorkName(); var row = sheet.GetRow(r + 2); for (int c = 0; c < 3; c++) { var cell = row.GetCell(c + 1); string v = ""; //excel列中的类型(最好在excel中设置的值都为字符串类型) switch (cell.CellType) { case CellType.Blank: break; case CellType.Boolean: v = cell.BooleanCellValue.ToString(); break; case CellType.String: v = cell.StringCellValue; break; case CellType.Unknown: default: v = cell.StringCellValue; break; } if (c == 0) { work.Name = v; } else if (c == 1) { work.Content = v; } else if (c == 2) { work.Flag = v; } } list.Add(work); } } return(list); }
private void button5_Click(object sender, EventArgs e) // submit { /*** * create json data * formate "환자의ID_처방전의ID":[{"key1":"val1", "key2":"val2"},{},{}] * RX class : {"key":"val"} * List<RX class> : [{},{}] * HashTable : "환자의 ID_처방전의 ID" : [{},{}] * creation date : 2017-12-22 2:39PM; ***/ System.Collections.Hashtable hash = new System.Collections.Hashtable(); foreach (ListViewItem item in this.listView1.Items) { RX obj = new RX(); obj.Col1 = item.SubItems[0].Text; obj.Col2 = item.SubItems[1].Text; obj.Col3 = item.SubItems[2].Text; obj.Col4 = item.SubItems[3].Text; obj.Col5 = item.SubItems[4].Text; obj.Col6 = item.SubItems[5].Text; if (hash != null && hash.ContainsKey(obj.Col1 + "_" + obj.Col2) != false) { ((List <RX>)hash[obj.Col1 + "_" + obj.Col2]).Add(obj); } else { List <RX> newList = new List <RX>(); newList.Add(obj); hash.Add(obj.Col1 + "_" + obj.Col2, newList); } } System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); var json = js.Serialize(hash); MessageBox.Show(json.ToString()); //traverse keys System.Collections.IDictionaryEnumerator ie = hash.GetEnumerator(); /*** * create new files and save information * formate "환자의ID_처방전의ID.txt" * creation date : 2017-12-22 2:39PM; ***/ while (ie.MoveNext()) { //MessageBox.Show((string)ie.Key); string[] substr = (ie.Key as string).Split('_').ToArray(); string dirName = @".\" + substr[0]; string fileName = dirName + @"\" + substr[1] + ".txt"; /*** * create new file ***/ if (System.IO.Directory.Exists(@dirName) != true) { //MessageBox.Show(@dirName); System.IO.Directory.CreateDirectory(dirName); } System.IO.FileStream fs = System.IO.File.OpenWrite(@fileName); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8); sw.Write(js.Serialize(hash[ie.Key]).ToString()); sw.Flush(); sw.Close(); } }