当前位置: 首页>>代码示例>>C#>>正文


C# Stream.CopyTo方法代码示例

本文整理汇总了C#中System.IO.Stream.CopyTo方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.CopyTo方法的具体用法?C# Stream.CopyTo怎么用?C# Stream.CopyTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.Stream的用法示例。


在下文中一共展示了Stream.CopyTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Send

        public void Send(string remoteUrl, IDictionary<string, string> headers, Stream data)
        {
            var request = WebRequest.Create(remoteUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers = Encode(headers);
            request.UseDefaultCredentials = true;
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                data.CopyTo(stream);
            }

            HttpStatusCode statusCode;

            //todo make the receiver send the md5 back so that we can double check that the transmission went ok
            using (var response = (HttpWebResponse) request.GetResponse())
            {
                statusCode = response.StatusCode;
            }

            Logger.Debug("Got HTTP response with status code " + statusCode);

            if (statusCode != HttpStatusCode.OK)
            {
                Logger.Warn("Message not transferred successfully. Trying again...");
                throw new Exception("Retrying");
            }
        }
开发者ID:ramonsmits,项目名称:NServiceBus.Gateway,代码行数:30,代码来源:HttpChannelSender.cs

示例2: Write

 /// <summary>
 /// Write - this write routine for mdat is used only when writing out an MP4 file.
 /// (See MP4StreamWriter.)
 /// </summary>
 /// <param name="writer"></param>
 public void Write(BoxWriter writer, Stream reader)
 {
     if (base.Size == 0UL)
       {
     base.Write(writer);
     reader.CopyTo(writer.BaseStream);
       }
       else
     using (new SizeCalculator(this, writer))
     {
         base.Write(writer);
         reader.CopyTo(writer.BaseStream);
     }
 }
开发者ID:ctapang,项目名称:GPUCyclops,代码行数:19,代码来源:MediaDataBox.cs

示例3: CreateOrAppendToFile

 public void CreateOrAppendToFile(string fileLocation, Stream stream)
 {
     var sourcePath = Path.Combine(DebugConfig.LocalStoragePath, fileLocation);
     var fileInfo = new FileInfo(sourcePath);
     if (fileInfo.Exists)
     {
         using (var streamWrite = fileInfo.Open(FileMode.Append, FileAccess.Write))
             stream.CopyTo(streamWrite);
     }
     else
     {
         using (var streamWrite = fileInfo.Open(FileMode.Create, FileAccess.Write))
             stream.CopyTo(streamWrite);
     }
 }
开发者ID:andrerpena,项目名称:Cerebello,代码行数:15,代码来源:LocalStorageService.cs

示例4: DownloadResult

        public DownloadResult( ILog logger, Stream zipContent )
        {
            File = new TemporaryFile( ".zip" );
            using( zipContent )
            using( var sw = System.IO.File.Open( File.Path, FileMode.Open ) )
                zipContent.CopyTo( sw );

            try
            {
                // open the zip file
                using( ZipFile zip = ZipFile.Read( File.Path ) )
                {
                    var manifestEntry = zip.Where( z => z.FileName == "manifest.xml" ).FirstOrDefault();
                    if( manifestEntry != null )
                    {
                        var ms = new MemoryStream();
                        manifestEntry.Extract( ms );
                        try
                        {
                            Manifest = HelpManifestData.Deserialize( ms );
                        }
                        catch( Exception ex )
                        {
                            logger.Error( "Unable to parse manifest", ex );
                            throw;
                        }
                    }
                }
            }
            catch( Exception ex )
            {
                logger.Error( "Unable to read downloaded help content as a zip file", ex );
                throw;
            }
        }
开发者ID:Invenietis,项目名称:ck-certified,代码行数:35,代码来源:DownloadResult.cs

示例5: ReadFromStreamAsync

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                MemoryStream stream = new MemoryStream();
                readStream.CopyTo(stream);

                IEnumerable<string> xContentHeader;
                var success = content.Headers.TryGetValues("X-Content-Type", out xContentHeader);

                if (!success)
                {
                    throw Error.BadRequest("POST to binary must provide a Content-Type header");
                }

                string contentType = xContentHeader.FirstOrDefault();

                Binary binary = new Binary();
                binary.Content = stream.ToArray();
                binary.ContentType = contentType;

                //ResourceEntry entry = ResourceEntry.Create(binary);
                //entry.Tags = content.Headers.GetFhirTags();
                return (object)binary;
            });
        }
开发者ID:Condeti,项目名称:spark,代码行数:26,代码来源:BinaryFormatter.cs

示例6: Resize

        public static Stream Resize(int width, int height, Stream image, string fileName)
        {
            Stream fileStream = new MemoryStream();
            Image tempImage = Bitmap.FromStream(image);
            long maxFactor = width * height;
            long imageFactor = tempImage.Width * tempImage.Height;

            if (maxFactor < imageFactor)
            {
                using (ImageResizer resizer = new ImageResizer())
                {
                    resizer.MimeType = Path.GetExtension(fileName);
                    resizer.SourceImage = tempImage;
                    resizer.Background = ColorTranslator.FromHtml("#fff");
                    resizer.Mode = ImageResizer.ResizeMode.KeepOriginalAspect;
                    resizer.Width = width;
                    resizer.Height = height;

                    resizer.Process();

                    resizer.ResultImage.Save(fileStream, tempImage.RawFormat);
                }
            }
            else
            {
                image.Seek(0, SeekOrigin.Begin);
                image.CopyTo(fileStream);
            }

            return fileStream;
        }
开发者ID:nhtera,项目名称:CrowdCMS,代码行数:31,代码来源:ImageUtils.cs

示例7: Store

		public string Store (string id, Stream stream)
		{
			EnsureOutput ();
			SetupEntry (zipOutput, ref id);
			stream.CopyTo (zipOutput);
			return id;
		}
开发者ID:vernon016,项目名称:mono,代码行数:7,代码来源:ZipStorage.cs

示例8: Decrypt

        public static MemoryStream Decrypt(Stream ciphertext)
        {
            var process = new Process
            {
                EnableRaisingEvents = false,
                StartInfo = new ProcessStartInfo
                {
                    FileName = @"C:\Program Files (x86)\GNU\GnuPG\pub\gpg2.exe",
                    Arguments = @"--decrypt",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true
                }
            };
            process.Start();

            var stdin = process.StandardInput;
            ciphertext.CopyTo(stdin.BaseStream);
            stdin.Close();

            var stdout = new MemoryStream();
            process.WaitForExit();
            process.StandardOutput.BaseStream.CopyTo(stdout);

            return stdout;
        }
开发者ID:mgolisch,项目名称:gpgkee,代码行数:28,代码来源:Gpg.cs

示例9: PushPackage

        public void PushPackage(string packageFileName, Stream packageStream)
        {
            packageFileName = PackageNameUtility.NormalizeFileName(packageFileName);

            var packageFile = _directory.GetFile(packageFileName);
            using (var destinationStream = packageFile.OpenWrite())
                packageStream.CopyTo(destinationStream);

            #pragma warning disable 612,618
            var zipPackage = new ZipFilePackage(packageFile);
            IndexDocument.Document.Root.Add(
                    new XElement("wrap",
                                 new XAttribute("name", zipPackage.Name),
                                 new XAttribute("version", zipPackage.Version),
                                 new XAttribute("semantic-version", zipPackage.SemanticVersion),
                                 new XElement("link",
                                              new XAttribute("rel", "package"),
                                              new XAttribute("href", packageFile.Name)),
                                 zipPackage.Dependencies.Select(x => new XElement("depends", x.ToString()))
                            ));
            #pragma warning restore 612,618

            SaveIndex(IndexDocument);

            return;
        }
开发者ID:modulexcite,项目名称:openwrap,代码行数:26,代码来源:FileSystemNavigator.cs

示例10: StoreFile

        public static RSResponse StoreFile(RSRequest rsRequest, Stream entity)
        {
            string extensionToAdd = "";

            //If file extension was not specified, make a good guess
            if (Path.GetExtension(rsRequest.LocalPath) == String.Empty)
            {
                extensionToAdd = rsRequest.ContentType.GetFileExtensionCandidates()[0];
            }

            //Add extension to the target file name (or don't)
            string newFileName = rsRequest.LocalPath + extensionToAdd;

            try
            {
                using (FileStream fs = File.OpenWrite(newFileName))
                {
                    entity.CopyTo(fs);
                }
            }
            catch (Exception ex)
            {
                return new StatusCodeResponse(HttpStatusCode.InternalServerError, ex.Message);
            }

            return new StatusCodeResponse(HttpStatusCode.Created);
        }
开发者ID:SteGriff,项目名称:ReServer,代码行数:27,代码来源:DocumentHandler.cs

示例11: Save

        public async Task<bool> Save(Stream stream, string path)
        {
            var api = await GetApi();

            var tempFilename = Path.GetTempFileName();

            using (var fileStream = File.Create(tempFilename))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(fileStream);
            }

            //var memoryStream = new MemoryStream();
            //var bytes = stream.ToArray();
            //File.WriteAllBytes(tempFilename, bytes);

            var directory = Path.GetDirectoryName(path);
            var filename = Path.GetFileName(path);

            var uploadedItem = await api.UploadFileAs(tempFilename, filename, directory);

            File.Delete(tempFilename);

            return uploadedItem != null;
        }
开发者ID:lluchs,项目名称:KeeAnywhere,代码行数:25,代码来源:OneDriveStorageProvider.cs

示例12: WriteStreamToFile

 public static void WriteStreamToFile(string filePath, Stream networkStream)
 {
     using (var fileStream = new FileStream(filePath, FileMode.Create))
     {
         networkStream.CopyTo(fileStream);
     }
 }
开发者ID:ballance,项目名称:Streaming,代码行数:7,代码来源:FileSreamer.cs

示例13: AddAttachment

		public Etag AddAttachment(string key, Etag etag, Stream data, RavenJObject headers)
		{
			Api.JetSetCurrentIndex(session, Files, "by_name");
			Api.MakeKey(session, Files, key, Encoding.Unicode, MakeKeyGrbit.NewKey);
			var isUpdate = Api.TrySeek(session, Files, SeekGrbit.SeekEQ);
			if (isUpdate)
			{
				var existingEtag = Etag.Parse(Api.RetrieveColumn(session, Files, tableColumnsCache.FilesColumns["etag"]));
				if (existingEtag != etag && etag != null)
				{
					throw new ConcurrencyException("PUT attempted on attachment '" + key +
						"' using a non current etag")
					{
						ActualETag = existingEtag,
						ExpectedETag = etag
					};
				}
			}
			else
			{
				if (data == null)
					throw new InvalidOperationException("When adding new attachment, the attachment data must be specified");

				if (Api.TryMoveFirst(session, Details))
					Api.EscrowUpdate(session, Details, tableColumnsCache.DetailsColumns["attachment_count"], 1);
			}

			Etag newETag = uuidGenerator.CreateSequentialUuid(UuidType.Attachments);
			using (var update = new Update(session, Files, isUpdate ? JET_prep.Replace : JET_prep.Insert))
			{
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["name"], key, Encoding.Unicode);
				if (data != null)
				{
					long written;
					using (var columnStream = new ColumnStream(session, Files, tableColumnsCache.FilesColumns["data"]))
					{
						if (isUpdate)
							columnStream.SetLength(0);
						using (var stream = new BufferedStream(columnStream))
						{
							data.CopyTo(stream);
							written = stream.Position;
							stream.Flush();
						}
					}
					if (written == 0) // empty attachment
					{
						Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["data"], new byte[0]);
					}
				}

				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["etag"], newETag.TransformToValueForEsentSorting());
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["metadata"], headers.ToString(Formatting.None), Encoding.Unicode);

				update.Save();
			}
			logger.Debug("Adding attachment {0}", key);

			return newETag;
		}
开发者ID:925coder,项目名称:ravendb,代码行数:60,代码来源:DocumentStorageActions.cs

示例14: Deploy

 private static TemporaryFile Deploy(Stream stream)
 {
     var tempFile = new TemporaryFile("0install-unit-tests");
     using (var fileStream = File.Create(tempFile))
         stream.CopyTo(fileStream);
     return tempFile;
 }
开发者ID:modulexcite,项目名称:0install-win,代码行数:7,代码来源:MsiExtractorTest.cs

示例15: Transform

        public void Transform(Stream stream)
        {
            if (mHash == null)
                return;

            stream.CopyTo(mCryptoStream);
        }
开发者ID:aiedail92,项目名称:DBBranchManager,代码行数:7,代码来源:HashTransformer.cs


注:本文中的System.IO.Stream.CopyTo方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。