WriteTo() публичный Метод

public WriteTo ( Stream stream ) : void
stream Stream
Результат void
Пример #1
0
        public static void Main(string[] args)
        {
            try
            {
                string assName = args [0];
                string outFile = Path.GetDirectoryName (Assembly.GetEntryAssembly ().CodeBase).Substring (5) + "/" + Path.GetFileName (args [0]) + ".xml";
                string htmlFile = outFile.Replace (".xml", ".html");

                XmlSerializer xs = new XmlSerializer (typeof(ReflectedContainer));
                ReflectedAssembly ass = new ReflectedAssembly (assName);

                Console.Write (string.Format ("Output XML reflection for {0} (to console and to {1})\n [Y/n] ?", assName, outFile));
                ConsoleKey input = Console.ReadKey ().Key;
                if (input != ConsoleKey.N)
                {
                    Console.WriteLine ("\n");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (XmlWriter xw = XmlWriter.Create (ms, XWSettings))
                        {
                            xs.Serialize (xw, new ReflectedContainer () { Assembly = ass });
                        }

                        if (File.Exists (outFile))
                            File.Delete (outFile);
                        using (Stream fs = File.OpenWrite (outFile), cs = Console.OpenStandardOutput ())
                        {
                            ms.WriteTo (fs);
                            ms.WriteTo (cs);
                        }

            //						if (File.Exists (htmlFile))
            //							File.Delete (htmlFile);
            //						using (Stream hs = File.OpenWrite (htmlFile))
            //						{
            //							using (XmlWriter xw = XmlWriter.Create(hs, XWSettings))
            //							{
            //								foreach (ReflectedType rt in ass.Types)
            //									rt.WriteHtml(xw);
            //							}
            //						}
                    }
                }
                else
                    Console.WriteLine ("Cancelled, exiting..");
            }
            catch (Exception ex)
            {
                Console.WriteLine ("! Exception : " + ex.ToString () + " : " + ex.Message);
            }
            finally
            {

            }
        }
Пример #2
0
        private string GetCameraImage(string url, string user, string password)
        {
            try
            {
                var client = new WebClient();
                client.UseDefaultCredentials = true;
                client.Credentials           = new NetworkCredential(user, password);
                var bytes = client.DownloadData(url);

                if (bytes.Length > 0)
                {
                    string fullpath           = System.Web.Hosting.HostingEnvironment.MapPath("~/imgs/") + string.Format("{0}.jpg", DateTime.Now.Ticks);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
                    System.IO.FileStream   fs = new System.IO.FileStream(fullpath, System.IO.FileMode.Create);
                    ms.WriteTo(fs);
                    ms.Close();
                    fs.Close();
                    fs.Dispose();
                    IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
                    return(_domainName + fullpath.Replace(System.Web.Hosting.HostingEnvironment.MapPath("~/imgs/"), "/imgs/").Replace(@"\", "/"));
                }

                return("");
            }
            catch (Exception ex)
            {
                _logger.Error("view-camera >> ERROR>" + ex.Message);
                return("");
            }
        }
Пример #3
0
		public static void Serve(string filePath, HttpContext context, string contentType)
		{
			CachePrep(ref filePath);
			lock (GetImageLock(filePath))
			{
				try
				{
					using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
					{
						using (MemoryStream memoryStream = new MemoryStream())
						{
							memoryStream.SetLength(fileStream.Length);
							fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
							memoryStream.WriteTo(context.Response.OutputStream);
							context.Response.ContentType = contentType;
						}
					}
				}
				catch (Exception ex)
				{
					ex.GetType();
					//The requested resource doesn't exist. Return HTTP status code 404.
					context.Response.StatusCode = (int)HttpStatusCode.NotFound;
					context.Response.StatusDescription = "Resource not found.";
				}

				RemoveImageLock(filePath);
			}
		}
Пример #4
0
        public void ExportDefinition(Project project)
        {
            TextWriter resultsWriter = new StringWriter();
            XmlTextWriter xslResultsWriter = new XmlTextWriter(resultsWriter);
            MemoryStream outStrm = new MemoryStream();

            XmlSerializer xs = new XmlSerializer(typeof(Project));
            TextWriter stringWriter = new StringWriter();
            XmlTextWriter xtr = new XmlTextWriter(stringWriter);

            string xmlnamespace = _Settings.XmlNameSpace;
            XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
            xns.Add("tt", xmlnamespace);
            try
            {
                //xs.Serialize(xtr, model, xns);
                xs.Serialize(outStrm, project, xns);
            }
            catch (Exception ee)
            {
                string m = ee.Message;
            }
            outStrm.Position = 0;

            FileStream fs = new FileStream(Settings.FileName, FileMode.OpenOrCreate, FileAccess.Write);
            outStrm.WriteTo(fs);
            fs.Flush();
            fs.Close();
            //string str = stringWriter.ToString();
            outStrm.Position = 0;
        }
Пример #5
0
 private void salvarArquivo(System.IO.MemoryStream stream, string saveTo)
 {
     using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
     {
         stream.WriteTo(file);
     }
 }
Пример #6
0
        /// <summary>
        /// Attempts to decompress the given input by letting all contained formats
        /// try to decompress the input.
        /// </summary>
        public override long Decompress(System.IO.Stream instream, long inLength, System.IO.Stream outstream)
        {
            byte[] inputData = new byte[instream.Length];
            instream.Read(inputData, 0, inputData.Length);

            foreach (CompressionFormat format in this.formats)
            {
                if (!format.SupportsDecompression)
                    continue;
                using (MemoryStream input = new MemoryStream(inputData))
                {
                    if (!format.Supports(input, inputData.Length))
                        continue;
                    MemoryStream output = new MemoryStream();
                    try
                    {
                        long decLength = format.Decompress(input, inputData.Length, output);
                        if (decLength > 0)
                        {
                            output.WriteTo(outstream);
                            return decLength;
                        }
                    }
                    catch (Exception) { continue; }
                }
            }

            throw new InvalidDataException("Input cannot be decompressed using the " + this.ShortFormatString + " formats.");
        }
    public void Writing_Whole_File_In_Streamed_Blocks_Should_Create_Exact_Copy()
    {
      //use an output stream which works with buffers
      StreamedBlockOutputStream os = new StreamedBlockOutputStream(Token, 15000, b => UploadHandler.WriteBlockStreamed(b));
      MemoryStream ms = new MemoryStream(SourceFileContents);
      ms.WriteTo(os);

      UploadHandler.CompleteTransfer(Token.TransferId);

      TargetFile.Refresh();
      FileAssert.AreEqual(SourceFilePath, TargetFilePath);


      TargetFile.Delete();
      InitToken();

      //use a source strem
      using(var fs = SourceFile.OpenRead())
      {
        fs.WriteTo(Token, SourceFile.Length, 10000, b => UploadHandler.WriteBlockStreamed(b));
        UploadHandler.CompleteTransfer(Token.TransferId);

        TargetFile.Refresh();
        FileAssert.AreEqual(SourceFilePath, TargetFilePath);
      }
    }
Пример #8
0
        private void DoCaptcha(HttpContext context)
        {
            Color f = ColorTranslator.FromHtml(CaptchaImage.FGColorDef);
            Color b = ColorTranslator.FromHtml(CaptchaImage.BGColorDef);
            Color n = ColorTranslator.FromHtml(CaptchaImage.NColorDef);

            Bitmap captchaImg = CaptchaImage.GetCaptchaImage(f, b, n);

            if (captchaImg == null) {
                context.Response.StatusCode = 404;
                context.Response.StatusDescription = "Not Found";
                context.ApplicationInstance.CompleteRequest();
                return;
            }

            context.Response.ContentType = "image/x-png";

            using (MemoryStream memStream = new MemoryStream()) {
                captchaImg.Save(memStream, ImageFormat.Png);
                memStream.WriteTo(context.Response.OutputStream);
            }
            context.Response.StatusCode = 200;
            context.Response.StatusDescription = "OK";
            context.ApplicationInstance.CompleteRequest();

            captchaImg.Dispose();
            context.Response.End();
        }
Пример #9
0
 public void SaveStream(System.IO.MemoryStream stream, string saveTo)
 {
     using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
     {
         stream.WriteTo(file);
     }
 }
Пример #10
0
        //Listing 17-3. .NET code that creates the document
        partial void DownloadTimesheet_Execute()
        {
            // Create a document in a new workspace
            DataWorkspace   workspace = new DataWorkspace();
            TimesheetReport rpt       =
                workspace.ApplicationData.TimesheetReports.AddNew();

            rpt.EngineerId = this.Engineers.SelectedItem.Id;
            workspace.ApplicationData.SaveChanges();

            // Show the save dialog box
            Dispatchers.Main.Invoke(() =>
            {
                System.IO.MemoryStream ms =
                    new System.IO.MemoryStream(rpt.ReportData);
                Dispatchers.Main.Invoke(() =>
                {
                    SaveFileDialog saveDialog  = new SaveFileDialog();
                    saveDialog.DefaultFileName = "Timesheet.docx";
                    if (saveDialog.ShowDialog() == true)
                    {
                        using (Stream fileStream = saveDialog.OpenFile())
                        {
                            ms.WriteTo(fileStream);
                        }
                    }
                });
            });
        }
Пример #11
0
        public IActionResult GetFileFromWebApi()
        {
            System.IO.MemoryStream ms = NpoiLib.NpoiExcelHelper.ExportExcel(GetData(), null);

            var FilePath = Path.Combine(_hostEnvironment.WebRootPath, Guid.NewGuid().ToString("N") + ".xlsx");
            //var fileBytes = ms.ToArray();//文件流Byte
            FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate);

            ms.WriteTo(fs);
            ms.Close();
            fs.Close();

            return(PhysicalFile(FilePath, "application/octet-stream", $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.xlsx"));

            //try {
            //    var stream = new FileStream(FilePath, FileMode.Open);
            //    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            //    response.Content = new StreamContent(stream);
            //    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            //    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            //    {
            //        FileName = Guid.NewGuid().ToString("N") + ".xlsx"
            //    };
            //    return response;
            //} catch {
            //    return new HttpResponseMessage(HttpStatusCode.NoContent);
            //}
        }
        public static void Run()
        {
            // ExStart:ExtractImagesStream
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();
            // Open input PDF
            PdfExtractor pdfExtractor = new PdfExtractor();
            pdfExtractor.BindPdf(dataDir+ "ExtractImages-Stream.pdf");

            // Extract images
            pdfExtractor.ExtractImage();
            // Get all the extracted images
            while (pdfExtractor.HasNextImage())
            {
                // Read image into memory stream
                MemoryStream memoryStream = new MemoryStream();
                pdfExtractor.GetNextImage(memoryStream);

                // Write to disk, if you like, or use it otherwise.
                FileStream fileStream = new
                FileStream(dataDir+ DateTime.Now.Ticks.ToString() + "_out.jpg", FileMode.Create);
                memoryStream.WriteTo(fileStream);
                fileStream.Close();
            }
            // ExEnd:ExtractImagesStream
        }
Пример #13
0
 private static void SaveStream(System.IO.MemoryStream stream, string saveTo)
 {
     using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
     {
         stream.WriteTo(file);
     }
 }
Пример #14
0
        IEnumerable<DavResource> MakeRequest(Uri uri, DavVerb verb)
        {
            using (var queryStream = new MemoryStream())
            {
                PrepareRequestXml(queryStream);

                long contentLength = queryStream.Length;

                HttpWebRequest request = PrepareWebRequest(uri, verb, contentLength);

                using (Stream s = request.GetRequestStream())
                {
                    queryStream.WriteTo(s);
                    s.Close();
                }

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        byte[] bytes = responseStream.ReadToEnd();

                        Trace.WriteLine(Encoding.UTF8.GetString(bytes));

                        using (var reader = new MemoryStream(bytes))
                        {
                            return ParseResponse(uri, reader);
                        }
                    }
                }
            }
        }
Пример #15
0
    private void DownloadReportAsPDF()
    {
        try
        {
            string          url         = this.Request.Form["btnValue"];
            HttpWebRequest  request     = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response    = (HttpWebResponse)request.GetResponse();
            String          ver         = response.ProtocolVersion.ToString();
            StreamReader    reader      = new StreamReader(response.GetResponseStream());
            string          htmlContent = reader.ReadToEnd();

            NReco.PdfGenerator.HtmlToPdfConverter obj = new NReco.PdfGenerator.HtmlToPdfConverter();
            obj.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
            obj.PageWidth   = 1200;
            obj.Zoom        = 1;
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            obj.GeneratePdfFromFile("http://www.google.com.br", null, stream);
            string respondentName = string.Empty;

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Report.pdf");
            Response.Buffer = true;
            stream.WriteTo(Response.OutputStream);
            Response.End();
        }
        catch (Exception ex)
        {
        }
    }
Пример #16
0
        /// <summary>
        /// Measure cipher performance in MB/s
        /// </summary>
        /// <param name="cipher">Cipher instance</param>
        /// <returns>Speed in MB/s</returns>
        public static string SpeedTest(ICipherAlgorithm cipher)
        {
            const int SAMPLE_SIZE_KB = 4;
            const int TEST_CYCLES = 1024;

            byte[] plainText = new byte[SAMPLE_SIZE_KB * 1024];
            byte[] key = new byte[cipher.KeyLength];
            byte[] iv = new byte[cipher.BlockSize];

            Random rng = new Random();
            rng.NextBytes(plainText);
            rng.NextBytes(key);
            rng.NextBytes(iv);

            CipherEngine engine = new CipherEngine(cipher);
            Stream cipherStream = engine.EncryptStream(new MemoryStream(), key, iv);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            for (int c = 0; c < TEST_CYCLES; c++) {
                using (MemoryStream plainTextStream = new MemoryStream(plainText)) {
                    plainTextStream.WriteTo(cipherStream);
                }
            }
            sw.Stop();

            return String.Format("{0} = {1:0.00} KB/s", cipher.Name, (float)((1000.0 * SAMPLE_SIZE_KB * TEST_CYCLES) / (sw.ElapsedMilliseconds * 1.0)));
        }
Пример #17
0
 private void MySaveDialogControl_ClosingDialog(object sender, CancelEventArgs e)
 {
     if (_memstream == null)
     {
         return;
     }
     System.IO.FileStream br = null;
     try
     {
         br = new FileStream(MSDialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
         _memstream.WriteTo(br);
         br.Flush();
         br.Close();
         e.Cancel = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, "Unable to save the file because:\n"
                         + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
         e.Cancel = true;
     }
     finally
     {
         if (br != null)
         {
             br.Dispose();
         }
         _memstream.Dispose();
         _memstream = null;
     }
 }
Пример #18
0
        private static IResult SaveToFile(this NativeIO.MemoryStream stream, string fileName, SaveOptions options = null)
        {
            try
            {
                var safeOptions = options;
                if (options == null)
                {
                    safeOptions = SaveOptions.Default;
                }

                string parsedFullFilenamePath = Path.PathResolver(fileName);
                string directoryName          = NativeIO.Path.GetDirectoryName(parsedFullFilenamePath);
                NativeIO.DirectoryInfo di     = new NativeIO.DirectoryInfo(directoryName);
                bool existDirectory           = di.Exists;
                if (!existDirectory)
                {
                    if (safeOptions.CreateFolderIfNotExist)
                    {
                        NativeIO.Directory.CreateDirectory(directoryName);
                    }
                }

                using (var fs = new NativeIO.FileStream(parsedFullFilenamePath, NativeIO.FileMode.Create, NativeIO.FileAccess.ReadWrite, NativeIO.FileShare.ReadWrite))
                {
                    stream.WriteTo(fs);
                }

                return(BooleanResult.SuccessResult);
            }
            catch (Exception ex)
            {
                return(BooleanResult.FromException(ex));
            }
        }
Пример #19
0
        /// <summary>
        /// Creates a redirect.
        /// </summary>
        /// <param name="redirectMapping">The redirect mapping.</param>
        public void CreateRedirect(IRedirectMapping redirectMapping)
        {
            var stream = new MemoryStream();
            var tempStream = new MemoryStream();
            using (var streamWriter = new StreamWriter(tempStream))
            {
                switch (redirectMapping.RedirectType)
                {
                    case RedirectType.Permanent:
                        streamWriter.WriteLine("HTTP/1.1 301 Moved Permanently");
                        break;
                    case RedirectType.Temporary:
                        streamWriter.WriteLine("HTTP/1.1 302 Found");
                        break;
                    default:
                        throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture,
                                                                  "The redirect type '{0}' is not supported.", redirectMapping.RedirectType));
                }

                streamWriter.WriteLine("Location: " + redirectMapping.Uri.AbsoluteUri);
                streamWriter.Flush();

                tempStream.Seek(0, SeekOrigin.Begin);
                tempStream.WriteTo(stream);
            }

            stream.Seek(0, SeekOrigin.Begin);

            this.OnStreamAvailable(stream);
        }
Пример #20
0
        private static void DownloadFile(string fileId)
        {
            try
            {
                var request = service.Files.Get(fileId);
                var stream  = new System.IO.MemoryStream();

                request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
                {
                    if (progress.Status == DownloadStatus.Completed)
                    {
                        FileStream file = new FileStream("d:\\zekiri.jpg", FileMode.Create, FileAccess.Write);
                        try
                        {
                            Console.WriteLine("Download complete.");
                            stream.WriteTo(file);
                        }
                        finally
                        {
                            file.Close();
                            stream.Close();
                        }
                    }
                };

                request.Download(stream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #21
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();

            //open input PDF
            PdfExtractor pdfExtractor = new PdfExtractor();
            pdfExtractor.BindPdf(dataDir+ "ExtractImages-Page.pdf");

            //set StartPage and EndPage properties to the page number to
            //you want to extract images from
            pdfExtractor.StartPage = 2;
            pdfExtractor.EndPage = 2;

            //extract images
            pdfExtractor.ExtractImage();
            //get extracted images
            while (pdfExtractor.HasNextImage())
            {
                //read image into memory stream
                MemoryStream memoryStream = new MemoryStream();
                pdfExtractor.GetNextImage(memoryStream);

                //write to disk, if you like, or use it otherwise.
                FileStream fileStream = new
                FileStream(dataDir+ DateTime.Now.Ticks.ToString() + ".jpg", FileMode.Create);
                memoryStream.WriteTo(fileStream);
                fileStream.Close();
            }
            
            
        }
Пример #22
0
		protected override void OnInit(EventArgs e) {
			int imageHeight = 50;
			int topPadding = 10; // top and bottom padding in pixels
			int sidePadding = 10; // side padding in pixels
			SolidBrush textBrush = new SolidBrush(ColorTranslator.FromHtml("#97AC88"));
			Font font = new Font("Verdana", 18);

			string text = Guid.NewGuid().ToString().Substring(0, 6);

			Bitmap bitmap = new Bitmap(500, 500);
			Graphics graphics = Graphics.FromImage(bitmap);
			SizeF textSize = graphics.MeasureString(text, font);

			bitmap.Dispose();
			graphics.Dispose();

			int bitmapWidth = sidePadding * 2 + (int)textSize.Width;
			bitmap = new Bitmap(bitmapWidth, imageHeight);
			graphics = Graphics.FromImage(bitmap);

			graphics.DrawString(text, font, textBrush, sidePadding, topPadding);

			this.Response.ContentType = "image/x-png";

			using (MemoryStream memStream = new MemoryStream()) {
				bitmap.Save(memStream, ImageFormat.Png);
				memStream.WriteTo(this.Response.OutputStream);
			}

			graphics.Dispose();
			bitmap.Dispose();

			this.Response.End();
		}
Пример #23
0
        protected void FlushResponse(HttpListenerContext context, FileStream stream)
        {
            if (stream.Length > 1024
                && context.Request.Headers.AllKeys.Contains("Accept-Encoding")
                && context.Request.Headers["Accept-Encoding"].Contains("gzip"))
            {
                using (var ms = new MemoryStream())
                {
                    using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
                    {
                        stream.CopyTo( zip );
                    }
                    ms.Position = 0;

                    context.Response.AddHeader("Content-Encoding", "gzip");
                    context.Response.ContentLength64 = ms.Length;
                    ms.WriteTo( context.Response.OutputStream );
                 }
            }
            else
            {
                context.Response.ContentLength64 = stream.Length;
                stream.CopyTo( context.Response.OutputStream );
            }

            context.Response.OutputStream.Close();
            context.Response.Close();
        }
Пример #24
0
        static void Main(string[] args)
        {
            MemoryStream ms = new MemoryStream();

            StreamWriter sw = new StreamWriter(ms);

            Console.WriteLine("Enter 'quit' on a blank line to exit.");
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "quit")
                    break;
                sw.WriteLine(input);
            }
            sw.Flush();

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForAssembly();

            IsolatedStorageFileStream fs = new IsolatedStorageFileStream("output.txt", FileMode.Create, isoStore);
            ms.WriteTo(fs);

            sw.Close();
            ms.Close();
            fs.Close();

            IsolatedStorageFileStream tr = new IsolatedStorageFileStream("output.txt", FileMode.Open, isoStore);
            StreamReader sr = new StreamReader(tr);
            Console.Write(sr.ReadToEnd());
            sr.Close();
            tr.Close();
        }
Пример #25
0
        private void SaveStream(System.IO.MemoryStream stream, string saveTo)
        {
            using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                stream.WriteTo(file);
            }
            DAL.Barcode_reader reader = new Barcode_reader();

            string text = reader.Decode(saveTo);

            string time     = saveTo.Substring(saveTo.Length - 1 - 9 - 3, 6);
            string hour     = time.Substring(0, 2);
            string minnutes = time.Substring(2, 2);
            string dayNight = time.Substring(4, 2);

            if (dayNight == "PM")
            {
                hour = (Int32.Parse(hour) + 12).ToString();
            }
            int      y        = saveTo.IndexOf("at") - saveTo.IndexOf("Barcodes") - 10;
            string   x        = saveTo.Substring(saveTo.IndexOf("Barcodes") + 9, y);
            DateTime dateTime = DateTime.Parse(x + " " + hour + ":" + minnutes + ":" + "00" + " " + dayNight);

            string[]       str = text.Split('-');
            ScannedProduct s   = new ScannedProduct(Int32.Parse(str[4]), str[3], dateTime, float.Parse(str[2]), Int32.Parse(str[1]));

            rep.saveProductFromDrive(s, str[0]);
        }
Пример #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string fName = ConfigurationManager.AppSettings["Code39Barcode.FontFamily"];

        PrivateFontCollection fCollection = new PrivateFontCollection();
        fCollection.AddFontFile(ConfigurationManager.AppSettings["Code39Barcode.FontFile"]);
        FontFamily fFamily = new FontFamily(fName, fCollection);
        Font f = new Font(fFamily, FontSize);

        Bitmap bmp = new Bitmap(Width, Height);
        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);
        Brush b = new SolidBrush(Color.Black);
        g.DrawString("*" + strPortfolioID + "*", f, b, 0, 0);

        //PNG format has no visible compression artifacts like JPEG or GIF, so use this format, but it needs you to copy the bitmap into a new bitmap inorder to display the image properly.  Weird MS bug.
        Bitmap bm = new Bitmap(bmp);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        Response.ContentType = "image/png";
        bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.WriteTo(Response.OutputStream);

        b.Dispose();
        bm.Dispose();
        Response.End();
    }
Пример #27
0
        public bool PutImageToCache(MemoryStream tile, MapType type, Point pos, int zoom)
        {
            FileStream fs = null;
            try
            {
                string fileName = GetFilename(type, pos, zoom, true);
                fs = new FileStream(fileName, FileMode.Create);
                tile.WriteTo(fs);
                tile.Flush();
                fs.Close();
                fs.Dispose();
                tile.Seek(0, SeekOrigin.Begin);

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error in FilePureImageCache.PutImageToCache:\r\n" + ex.ToString());
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                return false;
            }
        }
Пример #28
0
 private void SaveDownloadedFile(System.IO.MemoryStream stream, string path)
 {
     using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
     {
         stream.WriteTo(file);
     }
 }
Пример #29
0
        public JsonResult CopyImageToService(string file, string filename)
        {
            ItemResult <string> res = new ItemResult <string>();

            try
            {
                var index = filename.LastIndexOf("/");
                if (index > -1)
                {
                    filename = filename.Substring(index + 1);
                }
                //过滤特殊字符即可
                string dummyData = file.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
                if (dummyData.Length % 4 > 0)
                {
                    dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
                }
                byte[] filedata           = Convert.FromBase64String(dummyData);
                System.IO.MemoryStream ms = new System.IO.MemoryStream(filedata);
                System.IO.FileStream   fs = new System.IO.FileStream(Server.MapPath("~/upload/images/") + filename, System.IO.FileMode.Create);
                ms.WriteTo(fs);
                ms.Close();
                fs.Close();
                fs          = null;
                ms          = null;
                res.Success = true;
                res.Data    = filename;
            }
            catch (Exception ex)
            {
                res.Message = ex.Message;
            }
            return(Json(res));
        }
Пример #30
0
        public static void Descargar(HttpContext context,  string nombreArchivo, string contentType,string contenido = null, byte[] contenidoBytes=null)
        {
            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            
            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", nombreArchivo));
            // set content type
            context.Response.ContentType = contentType;

            if (!string.IsNullOrWhiteSpace(contenido))
            {
                // add headers
                context.Response.AddHeader("Content-Length", contenido.Length.ToString(CultureInfo.InvariantCulture));
                // do AppendLine binary data to responce stream
                context.Response.Write(contenido);
            }

            if (contenidoBytes != null)
            {
                // add headers
                context.Response.AddHeader("Content-Length", contenidoBytes.Length.ToString(CultureInfo.InvariantCulture));
                MemoryStream ms = new MemoryStream(contenidoBytes);
                context.Response.Buffer = true;
                ms.WriteTo(context.Response.OutputStream);
            }

            // finish process
            context.Response.Flush();
            context.Response.SuppressContent = true;
            context.ApplicationInstance.CompleteRequest();
        }
Пример #31
0
        /// <summary>
        /// Method used to crop image.
        /// </summary>
        /// <param name="inputImagePathString">input image path</param>
        /// <param name="outputImagePathName">ouput image path</param>
        /// <param name="x1">x</param>
        /// <param name="y1">y</param>
        /// <param name="width">widht of cropped image</param>
        /// <param name="height">height of cropped image</param>
        public static void CropImage(string inputImagePathString, String outputImagePathName, int x1, int y1, int width, int height)
        {
            byte[] photoBytes = File.ReadAllBytes(inputImagePathString);
            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new JpegFormat { Quality = 70 };
            Rectangle rectangle = new Rectangle(x1, y1, width, height);

            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        // Load, resize, set the format and quality and save an image.
                        imageFactory.Load(inStream)
                                    .Crop(rectangle)
                                    .Format(format)
                                    .Save(outStream);

                        FileStream fileStream = new FileStream(outputImagePathName, FileMode.Create);
                        outStream.WriteTo(fileStream);
                        fileStream.Close();
                    }
                    // Do something with the stream.
                    outStream.Close();
                }
            }
        }
        public string DownloadFile(string path, string type = @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            string format = null;

            if (type.Contains("pdf"))
            {
                format = @"application/pdf";
            }
            else

            {
                format = @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }

            var fileId = spreadSheetId;

            string result          = null;
            var    serviceDownload = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            //var req = serviceDownload.Files.Get(fileId);
            var req = serviceDownload.Files.Export(fileId, format);

            using (var stream = new System.IO.MemoryStream())
            {
                req.MediaDownloader.ProgressChanged +=
                    (IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                    case DownloadStatus.Downloading:
                    {
                        result = progress.BytesDownloaded.ToString();
                        break;
                    }

                    case DownloadStatus.Completed:
                    {
                        result = "Download complete.";
                        break;
                    }

                    case DownloadStatus.Failed:
                    {
                        result = "Download failed.";
                        break;
                    }
                    }
                };
                req.Download(stream);
                using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    stream.WriteTo(file);
                }
            }

            return(result);
        }
Пример #33
0
        public async Task Invoke(HttpContext context)
        {
            var memoryStream = new MemoryStream();
            var bodyStream = context.Response.Body;
            context.Response.Body = memoryStream;
            await _next?.Invoke(context);
            var request = context.Request;
            var response = context.Response;

            if(!string.IsNullOrWhiteSpace(request.Headers["X-XHR-Referer"]))
            {
                context.Response.Cookies.Append("request_method", request.Method, new CookieOptions { HttpOnly = false });
                if(context.Response.StatusCode == 301 || context.Response.StatusCode == 302)
                {
                    var uri = new Uri(response.Headers["Location"]);
                    if(uri.Host.Equals(request.Host.Value))
                    {
                        response.Headers["X-XHR-Redirected-To"] = response.Headers["Location"];
                    }
                }
            }
            memoryStream.WriteTo(bodyStream);
            await bodyStream.FlushAsync();
            memoryStream.Dispose();
            bodyStream.Dispose();
        }
Пример #34
0
        /**
         * Encode this {@link OcspStatusRequest} to a {@link Stream}.
         * 
         * @param output
         *            the {@link Stream} to encode to.
         * @throws IOException
         */
        public virtual void Encode(Stream output)
        {
            if (mResponderIDList == null || mResponderIDList.Count < 1)
            {
                TlsUtilities.WriteUint16(0, output);
            }
            else
            {
                MemoryStream buf = new MemoryStream();
                for (int i = 0; i < mResponderIDList.Count; ++i)
                {
                    ResponderID responderID = (ResponderID)mResponderIDList[i];
                    byte[] derEncoding = responderID.GetEncoded(Asn1Encodable.Der);
                    TlsUtilities.WriteOpaque16(derEncoding, buf);
                }
                TlsUtilities.CheckUint16(buf.Length);
                TlsUtilities.WriteUint16((int)buf.Length, output);
                buf.WriteTo(output);
            }

            if (mRequestExtensions == null)
            {
                TlsUtilities.WriteUint16(0, output);
            }
            else
            {
                byte[] derEncoding = mRequestExtensions.GetEncoded(Asn1Encodable.Der);
                TlsUtilities.CheckUint16(derEncoding.Length);
                TlsUtilities.WriteUint16(derEncoding.Length, output);
                output.Write(derEncoding, 0, derEncoding.Length);
            }
        }
Пример #35
0
        public async Task Dictionary_with_empty_string_as_key_should_fail_bulk_insert_request()
        {
            var jsonRequestFactory = new HttpJsonRequestFactory(25);
            using (var store = NewRemoteDocumentStore())
            {
                var url = String.Format("{0}/databases/{1}", store.Url, store.DefaultDatabase);
                using (ConnectionOptions.Expect100Continue(url))
                {
                    var operationUrl = "/bulkInsert?&operationId=" + Guid.NewGuid();
                    var createHttpJsonRequestParams = new CreateHttpJsonRequestParams(null, url + operationUrl, "POST", new OperationCredentials(String.Empty, CredentialCache.DefaultNetworkCredentials), new DocumentConvention());
                    var request = jsonRequestFactory.CreateHttpJsonRequest(createHttpJsonRequestParams);
                    
                    var response = await request.ExecuteRawRequestAsync((requestStream, tcs) => 
                    {
                        using (var bufferedStream = new MemoryStream())
                        {
                            long bytesWritten;
                            WriteToBuffer(bufferedStream, out bytesWritten);

                            var requestBinaryWriter = new BinaryWriter(requestStream);
                            requestBinaryWriter.Write((int)bufferedStream.Position);

                            bufferedStream.WriteTo(requestStream);
                            requestStream.Flush();
                            tcs.TrySetResult(null);
                        }
                    });

                    Assert.Equal(422, (int)response.StatusCode);
                }
            }
        }
Пример #36
0
    public void ExporttoExcel(DataTable table, string filename, string ExcelName)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer          = true;
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + ExcelName + ".xlsx");


        using (ExcelPackage pack = new ExcelPackage())
        {
            ExcelWorksheet ws = pack.Workbook.Worksheets.Add(filename);

            ws.Cells["A1"].LoadFromDataTable(table, true);
            var ms = new System.IO.MemoryStream();
            pack.SaveAs(ms);
            ms.WriteTo(HttpContext.Current.Response.OutputStream);
        }

        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
Пример #37
0
        public void Write(BitmapSource i, Stream s)
        {
            BitmapEncoder encoder = null;

            if (MimeType.Equals("image/jpeg"))
            {
                encoder = new JpegBitmapEncoder();
                ((JpegBitmapEncoder)encoder).QualityLevel = localSettings.Quality;
            }
            else if (MimeType.Equals("image/png"))
            {
                encoder = new PngBitmapEncoder();
            }
            else if (MimeType.Equals("image/gif"))
            {
                encoder = new GifBitmapEncoder();
                encoder.Palette = new BitmapPalette(i, 256);
            }

            encoder.Frames.Add(BitmapFrame.Create(i));

            using (MemoryStream outputStream = new MemoryStream())
            {
                encoder.Save(outputStream);
                outputStream.WriteTo(s);
            }
        }
        public void EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
        {
            var data = new byte[] { 1, 2, 3, 4 };

            using (var stream = new MemoryStream())
            {
                using (var zip = new ZipFile())
                {
                    zip.AddEntry(STR_TestBin, data);
                    zip.Save(stream);

                    stream.Position = 0;
                    using (var fs = new FileStream(@"C:\Users\Ivan.z\Documents\test.bin.zip", FileMode.OpenOrCreate))
                    {
                        fs.Position = 0;

                        stream.WriteTo(fs);
                    }
                }

                stream.Position = 0;

                using (var zip = ZipFile.Read(stream))
                {
                    using (var ms = new MemoryStream())
                    {
                        zip[STR_TestBin].Extract(ms);

                        var actual = ms.ToArray();

                        CollectionAssert.AreEquivalent(data, actual);
                    }
                }
            }
        }
Пример #39
0
        static void Main(string[] args)
        {
            MemoryStream m = new MemoryStream(64);
            Console.WriteLine("Lenth: {0}\tPosition: {1}\tCapacity: {2}",
                m.Length, m.Position, m.Capacity);

            for (int i = 0; i < 64; i++)
            {
                m.WriteByte((byte)i);
            }

            string s = "Foo";
            for (int i = 0; i < 3; i++)
            {
                m.WriteByte((byte)s[i]);
            }

            Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}",
                m.Length, m.Position, m.Capacity);

            Console.WriteLine("\nContents:");
            byte[] ba = m.GetBuffer();

            foreach (byte b in ba)
            {
                Console.Write("{0,-3}", b);
            }

            FileStream fs = new FileStream("Goo.txt", FileMode.Create, FileAccess.Write);
            m.WriteTo(fs);
            fs.Close();
            m.Close();

            Console.ReadLine();
        }
Пример #40
0
		public static void Main(string[] args)
		{
			// Notes:
			// 1. All referenced assemblies shall
			//    define [assembly:Obfuscation(feature = "script")]
			// 2. Turn off "optimize code" option in release build
			// 3. All used .net APIs must be defined by ScriptCoreLibJava
			// 4. Generics are not supported.
			// 5. Check post build event
			// 6. Build in releas build configuration for java version

			Console.WriteLine("This console application can run at .net and java virtual machine!");

			var port = 18080;

			Console.WriteLine("http://127.0.0.1:" + port);


			port.ToListener(
				s =>
				{
					var request = new byte[0x1000];
					var requestc = s.Read(request, 0, request.Length);

					// StreamReader would be nice huh
					// ScriptCoreLibJava does not have it yet

					Console.WriteLine("client request " + requestc);

					// if we get the file name wrong we get a bad error message to stdout
					var data = File.ReadAllBytes("HTMLPage1.htm");
					Console.WriteLine("data length " + data.Length);

					var m = new MemoryStream();

					m.WriteLineASCII("HTTP/1.1 200 OK");
					m.WriteLineASCII("Content-Type:	text/html; charset=utf-8");
					m.WriteLineASCII("Content-Length: " + data.Length);
					m.WriteLineASCII("Connection: close");


					m.WriteLineASCII("");
					m.WriteLineASCII("");
					Console.WriteLine("headers written");

					m.WriteBytes(data);
					Console.WriteLine("data written");

					var Text = Encoding.ASCII.GetString(m.ToArray());
					m.WriteTo(s);
					Console.WriteLine("flush");

					s.Flush();
					s.Close();
				}
			);

			Console.WriteLine("press enter to exit!");
			Console.ReadLine();
		}
Пример #41
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Read the input from the query string
            _percentage = float.Parse(Request.QueryString[ImageServerConstants.Pct]);
            _high = float.Parse(Request.QueryString[ImageServerConstants.High]);
            _low = float.Parse(Request.QueryString[ImageServerConstants.Low]);


            // set the ContentType appropriately, we are creating PNG image
            Response.ContentType = ImageServerConstants.ImagePng;

            // Load the background image
            Image bmp = Image.FromFile(Server.MapPath(ImageServerConstants.ImageURLs.UsageBar));
            Graphics graphics = Graphics.FromImage(bmp);
            graphics.SmoothingMode = SmoothingMode.AntiAlias;

            _width = bmp.Width;
            _height = bmp.Height;

            DrawUsageOverlay(ref graphics);

            // Save the image to memory stream (needed to do this if we are creating PNG image)
            MemoryStream MemStream = new MemoryStream();
            bmp.Save(MemStream, ImageFormat.Png);
            MemStream.WriteTo(Response.OutputStream);

            graphics.Dispose();
            bmp.Dispose();
        }
Пример #42
0
 public string CreateFile(string folder , string FileName , byte[] fs)
 {
     string path = DefaultValue.DEFAULT_ALBUM_ROOT_FILEPATH + folder;
     if (!Directory.Exists(path))
     {
         Directory.CreateDirectory(path);
     }
        try{
         ///���岢ʵ����һ���ڴ������Դ���ύ�������ֽ����顣
         MemoryStream m = new MemoryStream(fs);
         ///����ʵ���ļ����󣬱������ص��ļ���
         FileStream f = new FileStream( path + FileName, FileMode.Create);
         ///�����ڴ��������д�������ļ�
         m.WriteTo(f);
         m.Close();
         f.Close();
         f = null;
         m = null;
         return folder + FileName;
     }
     catch (Exception ex)
     {
         return null;
     }
 }
Пример #43
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var random    = new Random();
            var lstNumber = new List <string[]>();

            for (int k = 0; k < 200000; k++)
            {
                string s = string.Empty;
                for (int i = 0; i < 16; i++)
                {
                    s = String.Concat(s, random.Next(10).ToString());
                }
                lstNumber.Add(new string[] { s });
            }

            Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("ePIN_200000PMO.xlsx", System.Text.Encoding.UTF8));

            using (ExcelPackage pck = new ExcelPackage())
            {
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("200000PMOePINs");
                ws.Cells["A1"].LoadFromDataTable(ConvertListToDataTable(lstNumber), true);
                var ms = new System.IO.MemoryStream();
                pck.SaveAs(ms);
                ms.WriteTo(Response.OutputStream);
            }
        }
Пример #44
0
        public byte[] GetBytes()
        {
            byte[] bytes;
             using (MemoryStream ms = new MemoryStream())
             {
            TextHelper.StreamString(ms, Name);
            TextHelper.StreamString(ms, Location);
            TextHelper.StreamString(ms, Description);

            Int32 length;
            using (MemoryStream sensorsStream = new MemoryStream())
            {
               MessageHelper.SerializeSensorDescriptionsDataTimes(sensorsStream, Sensors);
               length = (int)sensorsStream.Length;
               ms.Write(BitConverter.GetBytes(length), 0, sizeof(Int32));
               sensorsStream.WriteTo(ms);
            }

            length = PictureBytes.Length;
            ms.Write(BitConverter.GetBytes(length), 0, sizeof(Int32));
            ms.Write(PictureBytes, 0, length);
            bytes = ms.ToArray();
             }
             return bytes;
        }
Пример #45
0
 public static void putPlugin(MemoryStream memStream, string pluginPath)
 {
     using (FileStream filePlugin = System.IO.File.Create(pluginPath))
     {
         memStream.WriteTo(filePlugin);
     }
 }
Пример #46
0
        public override void Close()
        {
            if (!_isClosed)
            {
                // Avoid writing back a value if opened with Read permissions.
                if (_zipArchive.Mode != ZipArchiveMode.Read)
                {
                    _stream.Position = 0;
                    // Write all of the buffer.
                    _zipArchiveEntryStream.Seek(0, SeekOrigin.Begin);
                    _zipArchiveEntryStream.SetLength(0);

                    _stream.WriteTo(_zipArchiveEntryStream);
                }

                _zipArchiveEntryStream.Flush();

                _stream.Dispose();
                _zipArchiveEntryStream.Dispose();

                _zipArchive.Dispose();
                _zipArchive = null;
                _isClosed   = true;
                GC.Collect();
            }
        }
Пример #47
0
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter("select address,postalCode ,fax from  customers", constr))
            {
                //DataTable table = new DataTable();
                //adapter.Fill(table);

                // foreach (DataRow row in table.Rows)
                //  {
                // string[] rowData = new string[] { table.Rows[0].ToString() };
                using (ExcelPackage pck = new ExcelPackage())
                {
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.ClearHeaders();
                    HttpContext.Current.Response.Buffer          = true;
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridData.xlsx");


                    string         filename = "test.xlsx";
                    ExcelWorksheet ws       = pck.Workbook.Worksheets.Add(filename);
                    DataTable      table    = new DataTable();
                    table.Columns.Add("No", typeof(int));
                    table.Columns.Add("Date", typeof(DateTime));
                    table.Rows.Add(1, DateTime.Now);
                    table.Rows.Add(2, DateTime.Now);
                    DataTable dt1 = table;
                    ws.Cells["A1"].LoadFromDataTable(dt1, true);
                    var ms = new System.IO.MemoryStream();
                    ws.Cells[2, 2, 3, 2].Style.Numberformat.Format = "yyyy-MM-dd";//format the date


                    pck.SaveAs(ms);



                    ms.WriteTo(HttpContext.Current.Response.OutputStream);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();


                    //ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
                    //ws.Row(1).Style.Font.Bold = true;
                    //ws.Cells["A1"].LoadFromDataTable(table, true);
                    //var stream = new MemoryStream(pck.GetAsByteArray());
                    //stream.WriteTo(Response.OutputStream);
                    //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    //Response.AddHeader("Content-Disposition", "attachment;filename=file_export_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx");
                    //Response.End();
                    //Response.Flush();
                }
                //  }
            }
        }
Пример #48
0
        public JsonResult UploadImg(string file)
        {
            string message = string.Empty;
            //过滤特殊字符即可
            string dummyData = file.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");

            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }
            byte[] filedata = Convert.FromBase64String(dummyData);

            //保存图片
            if (filedata.Length > 1048576)
            {
                message = "图片大小不能超过1M";
            }
            string fileextension = filedata[0].ToString() + filedata[1].ToString();

            if (fileextension == "7173")
            {
                fileextension = "gif";
            }
            else if (fileextension == "255216")
            {
                fileextension = "jpg";
            }
            else if (fileextension == "13780")
            {
                fileextension = "png";
            }
            else if (fileextension == "6677")
            {
                fileextension = "bmp";
            }
            else if (fileextension == "7373")
            {
                fileextension = "tif";
            }
            else
            {
                message = "上传的文件不是图片";
            }

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Ticks.ToString() + "." + fileextension;
            var    kb       = filedata.Length * 1.0 / 1024;
            string filePath = ApplicationContext.AppSetting.Image_Upload_Path + fileName;

            System.IO.MemoryStream ms = new System.IO.MemoryStream(filedata);
            System.IO.FileStream   fs = new System.IO.FileStream(Server.MapPath("~/upload/images/") + fileName, System.IO.FileMode.Create);
            ms.WriteTo(fs);
            ms.Close();
            fs.Close();
            fs = null;
            ms = null;
            return(Json(message));
        }
Пример #49
0
        private void btnGetItem_Click(object sender, EventArgs e)
        {
            //string id = lstOutput.Items[lstOutput.SelectedIndex].ToString();
            //string baseGetURL = "https://www.googleapis.com/drive/v3/files/";
            //string fullGetURL = baseGetURL + id;
            //Console.WriteLine(fullGetURL);

            //WebRequest wrGETURL;
            //wrGETURL = WebRequest.Create(fullGetURL);

            //Stream objStream;
            //objStream = wrGETURL.GetResponse().GetResponseStream();



            var fileId  = userDrive.fileIDList[lstOutput.SelectedIndex];
            var request = userDrive.Auth().Files.Get(fileId);
            var stream  = new System.IO.MemoryStream();



            // Add a handler which will be notified on progress changes.
            // It will notify on each chunk download and when the
            // download is completed or failed.
            request.MediaDownloader.ProgressChanged +=
                (IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case DownloadStatus.Downloading:
                {
                    Console.WriteLine(progress.BytesDownloaded);
                    break;
                }

                case DownloadStatus.Completed:
                {
                    Console.WriteLine("Download complete.");
                    break;
                }

                case DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream);
            FileStream downloadFile = new FileStream("C:\\Users\\Jonathan\\source\\repos\\DriveFilesTest\\DriveFiles\\Downloads\\" +
                                                     userDrive.fileNameList[lstOutput.SelectedIndex], FileMode.Create, FileAccess.Write);

            stream.WriteTo(downloadFile);
            downloadFile.Close();
            stream.Close();
        }
Пример #50
0
 private static void GuardarStreaming(System.IO.MemoryStream pStream, string pGuardarA)
 {
     if (!File.Exists(pGuardarA))
     {
         using (System.IO.FileStream file = new System.IO.FileStream(pGuardarA, System.IO.FileMode.Create, System.IO.FileAccess.Write))
         {
             pStream.WriteTo(file);
         }
     }
 }
Пример #51
0
 private void CopyFileStream(byte[] srcBuffer, string fileName)
 {
     using (var target = System.IO.File.Create(fileName))
     {
         using (var src = new System.IO.MemoryStream(srcBuffer, false))
         {
             src.WriteTo(target);
         }
     }
 }
Пример #52
0
        public static void Generate(DataTable dt)
        {
            try
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Buffer          = true;
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=WellQuailtyTracker_Forecast.xlsx");


                using (ExcelPackage pack = new ExcelPackage())
                {
                    ExcelWorksheet ws = pack.Workbook.Worksheets.Add("ExcelReport");

                    var    modelCells = ws.Cells["A1"];
                    var    modelRows  = dt.Rows.Count + 1;
                    string modelRange = "A1:AP" + modelRows.ToString();
                    var    modelTable = ws.Cells[modelRange];

                    var    UnLockCells = ws.Cells["C2"];
                    string UnLockRange = "C2:AP" + modelRows.ToString();


                    // Assign borders
                    modelTable.Style.Border.Top.Style    = ExcelBorderStyle.Thin;
                    modelTable.Style.Border.Left.Style   = ExcelBorderStyle.Thin;
                    modelTable.Style.Border.Right.Style  = ExcelBorderStyle.Thin;
                    modelTable.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;


                    // Fill worksheet with data to export
                    modelCells.LoadFromDataTable(dt, true);
                    modelTable.AutoFitColumns();

                    ws.Protection.IsProtected = true;
                    ws.Cells[2, 3, modelRows, 42].Style.Locked = false;

                    var ms = new System.IO.MemoryStream();
                    pack.SaveAs(ms);
                    ms.WriteTo(HttpContext.Current.Response.OutputStream);
                }

                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #53
0
        private void PoolMethod()
        {
            try
            {
                if (!this.httpListener.IsListening)
                {
                    return;
                }

                HttpListenerContext  context  = this.httpListener.GetContext();
                HttpListenerResponse response = context.Response;
                response.ContentType = "multipart/x-mixed-replace; boundary=--myboundary";
                Stream     responseStream = response.OutputStream;
                MessageImg arg            = new MessageImg();

                for (; ;)
                {
                    if (requestToStopTheThread)
                    {
                        break;
                    }

                    if (this.OnGetImage == null)
                    {
                        continue;
                    }

                    // Get image.
                    this.OnGetImage(this, arg);

                    MemoryStream imageStream = new MemoryStream();
                    JpegUtils.SaveJPG100(arg.Image, imageStream);

                    byte[]       headerBytes  = asciiEncodeing.GetBytes("\r\n--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length:" + imageStream.Length + "\r\n\r\n");
                    MemoryStream headerStream = new System.IO.MemoryStream(headerBytes);

                    headerStream.WriteTo(responseStream);

                    imageStream.WriteTo(responseStream);

                    responseStream.Flush();

                    this.FrameCount++;

                    System.Threading.Thread.Sleep(20);
                }
            }
            catch (Exception exception)
            {
                this.Stop();
            }

            this.Stop();
        }
Пример #54
0
        public ActionResult MergePDF()
        {
            string        firstPDFPath      = string.Empty;
            string        secondPDFPath     = string.Empty;
            string        thirdPDFPath      = string.Empty;
            var           myFileList        = new List <string>();
            long          fileTimeStamp     = DateTime.Now.ToFileTime(); // prepare temp folder
            int           counter           = 0;                         // used for creating files number wise
            string        mainDirectoryPath = Server.MapPath("~/Document");
            DirectoryInfo dir            = new DirectoryInfo(mainDirectoryPath);
            CommonService _commonService = new CommonService();

            try
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("~/Document/" + fileTimeStamp.ToString()));

                for (int i = 0; i < dir.GetFiles().Length; i++)
                {
                    firstPDFPath = Server.MapPath("~/Document/Test" + (i + 1) + ".pdf");

                    PdfReader _readerPayment = new PdfReader(firstPDFPath);

                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        PdfStamper stamper = new PdfStamper(_readerPayment, ms);
                        using (stamper)
                        {
                            Dictionary <string, string> info = _readerPayment.Info;
                            stamper.MoreInfo = info;
                            _commonService.SetPDFFields(stamper.AcroFields);
                        }
                        System.IO.MemoryStream msn  = new System.IO.MemoryStream(ms.ToArray());
                        System.IO.FileStream   file = new System.IO.FileStream(Server.MapPath("~/Document/" + fileTimeStamp.ToString() + "/" + (++counter) + ".pdf"), FileMode.Create, FileAccess.Write);
                        myFileList.Add(Server.MapPath("~/Document/" + fileTimeStamp.ToString() + "/" + (counter) + ".pdf"));
                        msn.WriteTo(file);
                        file.Close();
                        msn.Close();
                    }
                }
                string[] _allFiles = System.IO.Directory.GetFiles(Server.MapPath("~/Document/" + fileTimeStamp.ToString()));
                if (counter > 0 && myFileList.Count > 0)
                {
                    MergePDFs(Server.MapPath("~/Document/MainApp_" + fileTimeStamp + ".pdf"), _allFiles);
                }

                return(File(Server.MapPath("~/Document/MainApp_" + fileTimeStamp + ".pdf"), "application/pdf"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(View());
        }
Пример #55
0
        public async Task DownloadFile(string fileID, string fullPathAndFileName)
        {
            var request = _service.Files.Get(fileID);
            var stream  = new System.IO.MemoryStream();
            await request.DownloadAsync(stream);

            FileStream file = new FileStream(fullPathAndFileName, FileMode.Create, FileAccess.ReadWrite);

            stream.WriteTo(file);
            stream.Close();
            file.Close();
        }
Пример #56
0
        private void DownloadFileResource(File fileResource, string path, bool rootPath = true, bool overwrite = false)
        {
            if (rootPath)
            {
                path = path + fileResource.Name;
            }
            else
            {
                path = Path.Combine(path, fileResource.Name);
            }

            Logger.Info($"[Google Drive] Downloading {fileResource.Name}");
            if (fileResource.MimeType != "application/vnd.google-apps.folder")
            {
                if (System.IO.File.Exists(path))
                {
                    if (!overwrite)
                    {
                        Logger.Warn("[Google Drive] FILE EXISTS: " + path);
                        return;
                    }
                    else
                    {
                        System.IO.File.Delete(path);
                    }
                }

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(new FileInfo(path).DirectoryName);
                }

                var stream = new System.IO.MemoryStream();

                Service.Files.Get(fileResource.Id).Download(stream);
                System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                stream.WriteTo(file);

                file.Close();
            }
            else
            {
                System.IO.Directory.CreateDirectory(path);
                var subFolderItems = RessInFolder(fileResource.Id);

                foreach (var item in subFolderItems)
                {
                    DownloadFileResource(item, path, false);
                }
            }
        }
Пример #57
0
        public void Write(System.IO.MemoryStream imageStream)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.AppendLine();
            sb.AppendLine(Boundary);
            sb.AppendLine("Content-Type: image/jpeg");
            sb.AppendLine("Content-Length: " + imageStream.Length);
            sb.AppendLine();
            Write(sb.ToString());
            imageStream.WriteTo(Stream);
            Write("\r\n");

            Stream.Flush();
        }
Пример #58
0
 public static void downloadFile(byte[] bytes, string fileName, string fileMime)
 {
     try
     {
         System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
         System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + fileName));
         System.Web.HttpContext.Current.Response.AddHeader("Content-Type", fileMime);
         ms.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
         //System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
         System.Web.HttpContext.Current.Response.End();
     }
     catch (Exception ex)
     {
     }
 }
Пример #59
0
 public static bool SaveJaz(string data, string fileName)
 {
     try
     {
         System.IO.MemoryStream msSinkCompressed = new System.IO.MemoryStream();
         ZlibStream             zOut             = new ZlibStream(msSinkCompressed, CompressionMode.Compress, CompressionLevel.BestCompression, true);
         CopyStream(StringToMemoryStream(data), zOut);
         zOut.Close();
         FileStream file = new FileStream(fileName, FileMode.Create, System.IO.FileAccess.Write);
         msSinkCompressed.WriteTo(file);
         file.Close();
         return(true);
     }
     catch { }
     return(false);
 }
Пример #60
-1
        public static void exportToExcel(DataTable table, string tableName, string workSheetName, string fileName)
        {
            // Create the excel file and add worksheet
            XLWorkbook workBook = new XLWorkbook();
            IXLWorksheet workSheet = workBook.Worksheets.Add(workSheetName);

            // Hardcode title and contents locations
            IXLCell titleCell = workSheet.Cell(2, 2);
            IXLCell contentsCell = workSheet.Cell(3, 2);

            //Pretty-up the title
            titleCell.Value = tableName;
            titleCell.Style.Font.Bold = true;
            titleCell.Style.Fill.BackgroundColor = XLColor.CornflowerBlue;
            titleCell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

            // Merge cells for title
            workSheet.Range(titleCell, workSheet.Cell(2, table.Columns.Count + 1)).Merge();

            // Insert table contents, and adjust for content width
            contentsCell.InsertTable(table);
            workSheet.Columns().AdjustToContents(1, 75);

            // Create a new response and flush it to a memory stream
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx;");
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.SaveAs(stream);
                stream.WriteTo(response.OutputStream);
                stream.Close();
            }
            response.End();
        }