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


C# FileStream.CopyTo方法代码示例

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


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

示例1: CheckMail

        public void CheckMail()
        {
            try
            {
                string processLoc = dataActionsObject.getProcessingFolderLocation();
                StreamWriter st = new StreamWriter("C:\\Test\\_testings.txt");
                string emailId = "[email protected]";// ConfigurationManager.AppSettings["UserName"].ToString();
                if (emailId != string.Empty)
                {
                    st.WriteLine(DateTime.Now + " " + emailId);
                    st.Close();
                    ExchangeService service = new ExchangeService();
                    service.Credentials = new WebCredentials(emailId, "Sea2013");
                    service.UseDefaultCredentials = false;
                    service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                    Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                    SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    if (inbox.UnreadCount > 0)
                    {
                        ItemView view = new ItemView(inbox.UnreadCount);
                        FindItemsResults<Item> findResults = inbox.FindItems(sf, view);
                        PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients);
                        itempropertyset.RequestedBodyType = BodyType.Text;
                        //inbox.UnreadCount
                        ServiceResponseCollection<GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), itempropertyset);
                        MailItem[] msit = getMailItem(items, service);

                        foreach (MailItem item in msit)
                        {
                            item.message.IsRead = true;
                            item.message.Update(ConflictResolutionMode.AlwaysOverwrite);
                            foreach (Attachment attachment in item.attachment)
                            {
                                if (attachment is FileAttachment)
                                {
                                    string extName = attachment.Name.Substring(attachment.Name.LastIndexOf('.'));
                                    FileAttachment fileAttachment = attachment as FileAttachment;
                                    FileStream theStream = new FileStream(processLoc + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                    fileAttachment.Load(theStream);
                                    byte[] fileContents;
                                    MemoryStream memStream = new MemoryStream();
                                    theStream.CopyTo(memStream);
                                    fileContents = memStream.GetBuffer();
                                    theStream.Close();
                                    theStream.Dispose();
                                    Console.WriteLine("Attachment name: " + fileAttachment.Name + fileAttachment.Content + fileAttachment.ContentType + fileAttachment.Size);
                                }
                            }
                        }
                    }
                    DeleteMail(emailId);
                }
            }
            catch (Exception ex)
            {

            }
        }
开发者ID:virtuoso-pra,项目名称:ReadEmail,代码行数:58,代码来源:CheckEmail.cs

示例2: FlushResponse

        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();
        }
开发者ID:tekhedd,项目名称:Interspecific,代码行数:28,代码来源:Responder.cs

示例3: Load

 internal void Load(string filePath)
 {
     FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
     file.CopyTo(this.stream);
     file.Close();
     this.Seek(0, SeekOrigin.Begin); //Reset stream position to the beginning where the reading should start
 }
开发者ID:samuto,项目名称:designscript,代码行数:7,代码来源:FileStorage.cs

示例4: EncryptionTest

        public void EncryptionTest()
        {
            var key = Encoding.ASCII.GetBytes("20121109joyetechjoyetech20128850");

            byte[] actual;
            using (var decFileStream = new FileStream("Evic11.dec", FileMode.Open, FileAccess.Read))
            using (var firmware = new Firmware(key))
            {
                decFileStream.CopyTo(firmware.Stream);
                firmware.UpdateHeader();

                actual = new byte[firmware.BaseStream.Length];
                firmware.BaseStream.Seek(0, SeekOrigin.Begin);
                firmware.BaseStream.Read(actual, 0, actual.Length);
            }

            byte[] expected;
            using (var encFileStream = new FileStream("Evic11.enc", FileMode.Open, FileAccess.Read))
            {
                expected = new byte[actual.Length];
                encFileStream.Read(expected, 0, expected.Length);
            }

            CollectionAssert.AreEquivalent(expected, actual);
        }
开发者ID:bitterskittles,项目名称:NVaporWare,代码行数:25,代码来源:FirmwareTests.cs

示例5: Main

        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(Url);
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();

            using (var stream = response.GetResponseStream())
            {
                var ms = new MemoryStream();
                stream.CopyTo(ms);
                var buff = ms.ToArray();
            //                var image = Image.FromStream(stream);
            //                image.Save("text.jpg");
            //                stream.Position = 0;
                string hash = GetHash(buff);
                File.WriteAllBytes("test.jpg",buff);

                using (var ms3 = new MemoryStream())
                {
                    using (var fs = new FileStream("test.jpg", FileMode.Open))
                    {
                        fs.CopyTo(ms3);
                        var buff2 = ms3.ToArray();
                        var hash2 = GetHash(buff2);
                    }
                }
                var h = GetHash(File.ReadAllBytes("test.jpg"));

                using (var sr = new StreamReader(stream))
                {
                    string text = sr.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
            Console.ReadKey();
        }
开发者ID:ThinhTu,项目名称:TaoLao,代码行数:35,代码来源:Program.cs

示例6: ReadBlocksWithMemoryStream

        public void ReadBlocksWithMemoryStream()
        {
            var resources = new Dictionary<string, Resource>();
            var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files");
            var files = Directory.GetFiles(path, "*.*_c");

            if (files.Length == 0)
            {
                Assert.Fail("There are no files to test.");
            }

            foreach (var file in files)
            {
                var resource = new Resource();

                var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                var ms = new MemoryStream();
                fs.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);

                resource.Read(ms);

                resources.Add(Path.GetFileName(file), resource);
            }

            VerifyResources(resources);
        }
开发者ID:githubron726,项目名称:ValveResourceFormat,代码行数:27,代码来源:Test.cs

示例7: SaveCore

        /// <summary>
        /// Saves the data source to the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        protected override void SaveCore(Stream stream)
        {
            stream = Enforce.NotNull(stream, () => stream);

            // Copy the input stream to the output stream.
            try
            {
                string absolutepath = this.Mapping.Uri.AbsolutePath;

                string rootSign = "~";
                if (!absolutepath.StartsWith(rootSign))
                {
                    absolutepath = string.Concat(rootSign, absolutepath);
                }

                string mapped = HostingEnvironment.MapPath((absolutepath));

                var response = this.Container.Resolve<IRuntimeContext>().HttpResponse;

                using (FileStream inputStream =
                    new FileStream(mapped, FileMode.Open))
                {
                    response.AddHeader("content-length", inputStream.Length.ToString(CultureInfo.InvariantCulture));
                    inputStream.CopyTo(stream,
                        () => response.IsClientConnected,
                        () => this.OnDownloadFinished(new DownloadFinishedEventArgs { Mapping = this.Mapping, State = DownloadFinishedState.Succeeded }),
                        () => this.OnDownloadFinished(new DownloadFinishedEventArgs { Mapping = this.Mapping, State = DownloadFinishedState.Canceled }));
                }
            }
            catch (FileNotFoundException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (PathTooLongException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (IOException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (SecurityException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
        }
开发者ID:peterbucher,项目名称:silkveil,代码行数:64,代码来源:FileDataSource.cs

示例8: RenderExternalJavascript

 public static void RenderExternalJavascript(Stream responseStream, IRootPathProvider rootPath)
 {
     using (var js = new FileStream(Path.Combine(rootPath.GetRootPath(), "content/external.js"), FileMode.Open))
     {
         js.CopyTo(responseStream);
     }
 }
开发者ID:jdaigle,项目名称:CommentR,代码行数:7,代码来源:ResourcesModule.cs

示例9: Main

        static void Main(string[] args)
        {
            const int minimumFileLength = 65*1024;

            string inputFileName = null;
            if (args.Length >= 1) inputFileName = args[0];
            else
            {
                Console.WriteLine(@"Укажите путь к входному файлу");
                inputFileName = Console.ReadLine();
            }

            string outputFilePath = Path.Combine(Path.GetDirectoryName(inputFileName), "1.otl");

            using (
                Stream inputStream = new FileStream(inputFileName, FileMode.Open),
                    outputStream = new FileStream(outputFilePath, FileMode.Create),
                    headerStream = new MemoryStream(Resources.header)
                )
            {
                headerStream.CopyTo(outputStream);
                inputStream.CopyTo(outputStream);
                while (outputStream.Length < minimumFileLength) outputStream.WriteByte(0xff);
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Готово");
            Console.ResetColor();
            Console.ReadLine();
        }
开发者ID:NpoSaut,项目名称:netBinToOtlConverter,代码行数:29,代码来源:Program.cs

示例10: backgroundLoadFileWorker_DoWork

 /// <summary>
 /// DoWork непосредственно выполняющий считывание указанного в диалоге открытия файл.
 /// Также он отправляет файл в первый по очереди сокет
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void backgroundLoadFileWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     try {
         fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
         using (MemoryStream memoryStream = new MemoryStream())
         {
             fs.CopyTo(memoryStream);
             memoryStream.Position = 0;
             MyListener list = new MyListener();
             list.Sender(memoryStream, g_host, g_port);
         }
         //Thread.Sleep(1000); //чтобы успеть посмотреть
         //fs.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "File operation failed",
         MessageBoxButtons.OK,
         MessageBoxIcon.Error);
     }
     finally
     {
         fs.Close();
     }
 }
开发者ID:cImentik,项目名称:PictureSockets,代码行数:31,代码来源:Form1.cs

示例11: DecryptFile

        public void DecryptFile(string sourceFilename, string destinationFilename, string password)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
            aes.Key = key.GetBytes(aes.KeySize / 8);
            aes.IV = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;
            ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);

            using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                {
                    try
                    {
                        using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            source.CopyTo(cryptoStream);
                        }
                    }
                    catch (CryptographicException exception)
                    {
                        if (exception.Message == "Padding is invalid and cannot be removed.")
                            throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                        else
                            throw;
                    }
                }
            }
        }
开发者ID:tejashwikalptaru,项目名称:csharp-clamAV-antivirus,代码行数:33,代码来源:Quarantine.cs

示例12: GetDimensions

        /// <summary>
        /// Gets the dimensions of an image.
        /// </summary>
        /// <param name="path">The path of the image to get the dimensions of.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>The dimensions of the specified image.</returns>
        /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
        public static Size GetDimensions(string path, ILogger logger)
        {
            try
            {
                using (var fs = File.OpenRead(path))
                {
                    using (var binaryReader = new BinaryReader(fs))
                    {
                        return GetDimensions(binaryReader);
                    }
                }
            }
            catch
            {
                logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
            }

            // Buffer to memory stream to avoid image locking file
            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var memoryStream = new MemoryStream())
                {
                    fs.CopyTo(memoryStream);

                    // Co it the old fashioned way
                    using (var b = Image.FromStream(memoryStream, true, false))
                    {
                        return b.Size;
                    }
                }
            }
        }
开发者ID:Kampari,项目名称:MediaBrowser,代码行数:39,代码来源:ImageHeader.cs

示例13: Execute

 public override bool Execute()
 {
     // Originally taken from https://peteris.rocks/blog/creating-release-zip-archive-with-msbuild/
       // Then modified not to be inline anymore
       try
       {
     using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
     using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
     {
       foreach (ITaskItem fileItem in Files)
       {
     string filename = fileItem.ItemSpec;
     using (Stream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
     using (Stream fileStreamInZip = archive.CreateEntry(new FileInfo(filename).Name).Open())
       fileStream.CopyTo(fileStreamInZip);
       }
     }
     return true;
       }
       catch (Exception ex)
       {
     Log.LogErrorFromException(ex);
     return false;
       }
 }
开发者ID:csf-dev,项目名称:ZPT-Sharp,代码行数:25,代码来源:CreateZipArchive.cs

示例14: GetByteArrayFromFile

        public static byte[] GetByteArrayFromFile(string logoFile)
        {
            var logoData = new byte[0];

            try
            {
                if (File.Exists(logoFile))
                {
                    using (var fileStream = new FileStream(logoFile, FileMode.Open))
                    {
                        using (var ms = new MemoryStream())
                        {
                            fileStream.CopyTo(ms);
                            logoData = ms.ToArray();
                        }
                    }
                }

            }
            catch (Exception)
            {
               //Log
            }

            return logoData;
        }
开发者ID:Jo3-16,项目名称:FMA,代码行数:26,代码来源:FileHelper.cs

示例15: WriteTo

 public override void WriteTo(HttpListenerResponse resp)
 {
     base.WriteTo(resp);
     FileStream fs = new FileStream(_file, FileMode.Open);
     fs.CopyTo(resp.OutputStream);
     fs.Close();
 }
开发者ID:todd-x86,项目名称:sharpserver,代码行数:7,代码来源:FileResponse.cs


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