C# FileStream.Read的代码示例

通过代码示例来学习C# FileStream.Read方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


FileStream.Read是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的FileStream.Read() 已经帮大家高亮显示了,大家可以重点学习FileStream.Read() 方法的写法,从而快速掌握该方法的应用。

FileStream.Read的代码示例1 - LoadDocumentWithStream()

    using System.IO;

    public static void LoadDocumentWithStream()
    {
      using( var fs = new FileStream( DocumentSample.DocumentSampleResourcesDirectory + @"First.docx", FileMode.Open, FileAccess.Read, FileShare.Read ) )
      {
        using( var doc = DocX.Load( fs ) )
        {
          // Add a title
          doc.InsertParagraph( 0, "Load Document with Stream", false ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

          // Insert a Paragraph into this document.
          var p = doc.InsertParagraph();

          // Append some text and add formatting.
          p.Append( "A small paragraph was added." );

          doc.SaveAs( DocumentSample.DocumentSampleOutputDirectory + @"LoadDocumentWithStream.docx" );
        }
      }
    }
    

开发者ID:xceedsoftware,项目名称:DocX,代码行数:21,代码来源:DocumentSample.cs

在LoadDocumentWithStream()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例2 - AddPicture()

    using System.IO;

    #endregion

    #region Public Methods

    /// 
    /// Add a picture loaded from disk or stream to a document.
    /// 
    public static void AddPicture()
    {
      Console.WriteLine( "\tAddPicture()" );

      // Create a document.
      using( var document = DocX.Create( ImageSample.ImageSampleOutputDirectory + @"AddPicture.docx" ) )
      {
        // Add a title
        document.InsertParagraph( "Adding Pictures" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

        // Add a simple image from disk.
        var image = document.AddImage( ImageSample.ImageSampleResourcesDirectory + @"balloon.jpg" );
        var picture = image.CreatePicture( 112.5f, 112.5f );
        var p = document.InsertParagraph( "- Here is a simple picture added from disk:\n" );
        p.AppendPicture( picture );

        // Insert incremental "Figure 1" under picture by Picture public method.
        picture.InsertCaptionAfterSelf( "Figure" );

        p.SpacingAfter( 40 );

        // Add a rotated image from disk and set some alpha( 0 to 1 ).
        var rotatedPicture = image.CreatePicture( 112f, 112f );
        rotatedPicture.Rotation = 25;

        var p2 = document.InsertParagraph( "- Here is the same picture added from disk, but rotated:\n" );
        p2.AppendPicture( rotatedPicture );

        // Insert incremental "Figure 2" under picture by Paragraph public method.
        p2 = p2.InsertCaptionAfterSelf( "Figure" );

        p2.SpacingAfter( 40 );

        // Add a simple image from a stream
        var streamImage = document.AddImage( new FileStream( ImageSample.ImageSampleResourcesDirectory + @"balloon.jpg", FileMode.Open, FileAccess.Read ) );
        var pictureStream = streamImage.CreatePicture( 112f, 112f );
        var p3 = document.InsertParagraph( "- Here is the same picture added from a stream:\n" );
        p3.AppendPicture( pictureStream );

        // Insert incremental "Figure 3" under picture by Paragraph public method.
        p3.InsertCaptionAfterSelf( "Figure" );

        document.Save();
        Console.WriteLine( "\tCreated: AddPicture.docx\n" );
      }
    }
    

开发者ID:xceedsoftware,项目名称:DocX,代码行数:55,代码来源:ImageSample.cs

在AddPicture()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例3 - FilesAreBufferedAndCanBeFlushed()

    using System.IO;

        [TestCaseSource(typeof(FileRunnersAndFolders), nameof(FileRunnersAndFolders.Runners))]
        public void FilesAreBufferedAndCanBeFlushed(FileSystemRunner fileSystem, string parentFolder)
        {
            string filename = Path.Combine(parentFolder, "FilesAreBufferedAndCanBeFlushed");
            string filePath = this.Enlistment.GetVirtualPathTo(filename);

            byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Some test data");

            using (FileStream writeStream = File.Open(filePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                writeStream.Write(buffer, 0, buffer.Length);

                using (FileStream readStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    readStream.Length.ShouldEqual(0);
                    writeStream.Flush();
                    readStream.Length.ShouldEqual(buffer.Length);

                    byte[] readBuffer = new byte[buffer.Length];
                    readStream.Read(readBuffer, 0, readBuffer.Length).ShouldEqual(readBuffer.Length);
                    readBuffer.ShouldMatchInOrder(buffer);
                }
            }

            fileSystem.DeleteFile(filePath);
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:BasicFileSystemTests.cs

在FilesAreBufferedAndCanBeFlushed()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例4 - CheckoutBranchWithOpenHandleBlockingRepoMetdataUpdate()

    using System.IO;

        [TestCase]
        public void CheckoutBranchWithOpenHandleBlockingRepoMetdataUpdate()
        {
            this.ControlGitRepo.Fetch(GitRepoTests.ConflictSourceBranch);
            this.ControlGitRepo.Fetch(GitRepoTests.ConflictTargetBranch);

            ManualResetEventSlim testReady = new ManualResetEventSlim(initialState: false);
            ManualResetEventSlim fileLocked = new ManualResetEventSlim(initialState: false);
            Task task = Task.Run(() =>
            {
                int attempts = 0;
                while (attempts < 100)
                {
                    try
                    {
                        using (FileStream stream = new FileStream(Path.Combine(this.Enlistment.DotGVFSRoot, "databases", "RepoMetadata.dat"), FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            fileLocked.Set();
                            testReady.Set();
                            Thread.Sleep(15000);
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        ++attempts;
                        Thread.Sleep(50);
                    }
                }

                testReady.Set();
            });

            // Wait for task to acquire the handle
            testReady.Wait();
            fileLocked.IsSet.ShouldBeTrue("Failed to obtain exclusive file handle.  Exclusive handle required to validate behavior");

            try
            {
                this.ValidateGitCommand("checkout " + GitRepoTests.ConflictTargetBranch);
            }
            catch (Exception)
            {
                // If the test fails, we should wait for the Task to complete so that it does not keep a handle open
                task.Wait();
                throw;
            }
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:50,代码来源:CheckoutTests.cs

在CheckoutBranchWithOpenHandleBlockingRepoMetdataUpdate()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例5 - GetPersistedValue()

    using System.IO;

        private static string GetPersistedValue(string dotGVFSRoot, string key)
        {
            string metadataPath = Path.Combine(dotGVFSRoot, RepoMetadataName);
            string json;
            using (FileStream fs = new FileStream(metadataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
            using (StreamReader reader = new StreamReader(fs))
            {
                while (!reader.EndOfStream)
                {
                    json = reader.ReadLine();
                    json.Substring(0, 2).ShouldEqual("A ");

                    KeyValuePair kvp = JsonConvert.DeserializeObject>(json.Substring(2));
                    if (kvp.Key == key)
                    {
                        return kvp.Value;
                    }
                }
            }

            return null;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:24,代码来源:GVFSHelpers.cs

在GetPersistedValue()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例6 - GetIndexHash()

    using System.IO;

        private byte[] GetIndexHash()
        {
            if (this.shouldHashIndex)
            {
                using (Stream fileStream = new FileStream(this.indexLockPath, FileMode.Open, FileAccess.Read, FileShare.Write))
                using (HashingStream hasher = new HashingStream(fileStream))
                {
                    hasher.CopyTo(Stream.Null);
                    return hasher.Hash;
                }
            }

            return new byte[20];
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:16,代码来源:GitIndexGenerator.cs

在GetIndexHash()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例7 - OpenIndexForRead()

    using System.IO;

        public virtual FileSystemTaskResult OpenIndexForRead()
        {
            if (!File.Exists(this.indexPath))
            {
                EventMetadata metadata = CreateEventMetadata();
                this.context.Tracer.RelatedError(metadata, "AcquireIndexLockAndOpenForWrites: Can't open the index because it doesn't exist");

                return FileSystemTaskResult.FatalError;
            }

            this.projectionParseComplete.Wait();

            FileSystemTaskResult result = FileSystemTaskResult.FatalError;
            try
            {
                this.indexFileStream = new FileStream(this.indexPath, FileMode.Open, FileAccess.Read, FileShare.Read, IndexFileStreamBufferSize);
                result = FileSystemTaskResult.Success;
            }
            catch (IOException e)
            {
                EventMetadata metadata = CreateEventMetadata(e);
                this.context.Tracer.RelatedWarning(metadata, "IOException in AcquireIndexLockAndOpenForWrites (Retryable)");
                result = FileSystemTaskResult.RetryableError;
            }
            catch (Exception e)
            {
                EventMetadata metadata = CreateEventMetadata(e);
                this.context.Tracer.RelatedError(metadata, "Exception in AcquireIndexLockAndOpenForWrites (FatalError)");
                result = FileSystemTaskResult.FatalError;
            }

            return result;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:35,代码来源:GitIndexProjection.cs

在OpenIndexForRead()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Read的代码示例8 - TryWriteTempFile()

    using System.IO;

        public virtual bool TryWriteTempFile(
            ITracer tracer,
            Stream source,
            string tempFilePath,
            out long fileLength,
            out Task flushTask,
            bool throwOnError = false)
        {
            fileLength = 0;
            flushTask = null;
            try
            {
                Stream fileStream = null;

                try
                {
                    fileStream = this.fileSystem.OpenFileStream(
                        tempFilePath,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.Read,
                        callFlushFileBuffers: false); // Any flushing to disk will be done asynchronously

                    StreamUtil.CopyToWithBuffer(source, fileStream);
                    fileLength = fileStream.Length;

                    if (this.Enlistment.FlushFileBuffersForPacks)
                    {
                        // Flush any data buffered in FileStream to the file system
                        fileStream.Flush();

                        // FlushFileBuffers using FlushAsync
                        // Do this last to ensure that the stream is not being accessed after it's been disposed
                        flushTask = fileStream.FlushAsync().ContinueWith((result) => fileStream.Dispose());
                    }
                }
                finally
                {
                    if (flushTask == null && fileStream != null)
                    {
                        fileStream.Dispose();
                    }
                }

                this.ValidateTempFile(tempFilePath, tempFilePath);
            }
            catch (Exception ex)
            {
                if (flushTask != null)
                {
                    flushTask.Wait();
                    flushTask = null;
                }

                this.CleanupTempFile(this.Tracer, tempFilePath);

                if (tracer != null)
                {
                    EventMetadata metadata = CreateEventMetadata(ex);
                    metadata.Add("tempFilePath", tempFilePath);
                    tracer.RelatedWarning(metadata, $"{nameof(this.TryWriteTempFile)}: Exception caught while writing temp file", Keywords.Telemetry);
                }

                if (throwOnError)
                {
                    throw;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:77,代码来源:GitObjects.cs

在TryWriteTempFile()方法中,FileStream的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

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