C# StreamReader.Read的代码示例

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

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


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

StreamReader.Read的代码示例1 - 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()方法中,StreamReader的代码示例类中的Read的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamReader.Read的代码示例2 - ServiceLogContainsUpgradeMessaging()

    using System.IO;

        private bool ServiceLogContainsUpgradeMessaging()
        {
            // This test checks for the upgrade timer start message in the Service log
            // file. GVFS.Service should schedule the timer as it starts.
            string expectedTimerMessage = "Checking for product upgrades. (Start)";
            string serviceLogFolder = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                "GVFS",
                GVFSServiceProcess.TestServiceName,
                "Logs");
            DirectoryInfo logsDirectory = new DirectoryInfo(serviceLogFolder);
            FileInfo logFile = logsDirectory.GetFiles()
                .OrderByDescending(f => f.LastWriteTime)
                .FirstOrDefault();

            if (logFile != null)
            {
                using (StreamReader fileStream = new StreamReader(File.Open(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    string nextLine = null;
                    while ((nextLine = fileStream.ReadLine()) != null)
                    {
                        if (nextLine.Contains(expectedTimerMessage))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
    

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

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

StreamReader.Read的代码示例3 - ModifiedPathsFromChangesInsideRepoSavedAfterRemount()

    using System.IO;

        [TestCaseSource(typeof(FileSystemRunner), nameof(FileSystemRunner.Runners))]
        public void ModifiedPathsFromChangesInsideRepoSavedAfterRemount(FileSystemRunner fileSystem)
        {
            string[] expectedModifiedFilesContentsAfterRemount =
                {
                    @"A .gitattributes",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(FileToAdd)}",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(FileToUpdate)}",
                    $"A {FileToDelete}",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(FileToRename)}",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(RenameFileTarget)}",
                    $"A {FolderToCreate}/",
                    $"A {RenameNewDotGitFileTarget}",
                    $"A {FolderToDelete}/",
                };

            string fileToAdd = this.Enlistment.GetVirtualPathTo(FileToAdd);
            fileSystem.WriteAllText(fileToAdd, "Contents for the new file");

            string fileToUpdate = this.Enlistment.GetVirtualPathTo(FileToUpdate);
            fileSystem.AppendAllText(fileToUpdate, "// Testing");

            string fileToDelete = this.Enlistment.GetVirtualPathTo(FileToDelete);
            fileSystem.DeleteFile(fileToDelete);
            fileToDelete.ShouldNotExistOnDisk(fileSystem);

            string fileToRename = this.Enlistment.GetVirtualPathTo(FileToRename);
            fileSystem.MoveFile(fileToRename, this.Enlistment.GetVirtualPathTo(RenameFileTarget));

            string folderToCreate = this.Enlistment.GetVirtualPathTo(FolderToCreate);
            fileSystem.CreateDirectory(folderToCreate);

            string folderToRename = this.Enlistment.GetVirtualPathTo(FolderToRename);
            fileSystem.CreateDirectory(folderToRename);
            string folderToRenameTarget = this.Enlistment.GetVirtualPathTo(RenameFolderTarget);
            fileSystem.MoveDirectory(folderToRename, folderToRenameTarget);

            // Deleting the new folder will remove it from the modified paths file
            fileSystem.DeleteDirectory(folderToRenameTarget);
            folderToRenameTarget.ShouldNotExistOnDisk(fileSystem);

            // Moving a file from the .git folder to the working directory should add the file to the modified paths
            string dotGitfileToAdd = this.Enlistment.GetVirtualPathTo(DotGitFileToCreate);
            fileSystem.WriteAllText(dotGitfileToAdd, "Contents for the new file in dot git");
            fileSystem.MoveFile(dotGitfileToAdd, this.Enlistment.GetVirtualPathTo(RenameNewDotGitFileTarget));

            string folderToDeleteFullPath = this.Enlistment.GetVirtualPathTo(FolderToDelete);
            fileSystem.WriteAllText(Path.Combine(folderToDeleteFullPath, "NewFile.txt"), "Contents for new file");
            string newFileToDelete = Path.Combine(folderToDeleteFullPath, "NewFileToDelete.txt");
            fileSystem.WriteAllText(newFileToDelete, "Contents for new file");
            fileSystem.DeleteFile(newFileToDelete);
            fileSystem.WriteAllText(Path.Combine(folderToDeleteFullPath, "CreateCommonVersionHeader.bat"), "Changing the file contents");
            fileSystem.DeleteFile(Path.Combine(folderToDeleteFullPath, "RunUnitTests.bat"));

            fileSystem.DeleteDirectory(folderToDeleteFullPath);
            folderToDeleteFullPath.ShouldNotExistOnDisk(fileSystem);

            // Remount
            this.Enlistment.UnmountGVFS();
            this.Enlistment.MountGVFS();

            this.Enlistment.WaitForBackgroundOperations();

            string modifiedPathsDatabase = Path.Combine(this.Enlistment.DotGVFSRoot, TestConstants.Databases.ModifiedPaths);
            modifiedPathsDatabase.ShouldBeAFile(fileSystem);
            using (StreamReader reader = new StreamReader(File.Open(modifiedPathsDatabase, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                reader.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).OrderBy(x => x)
                    .ShouldMatchInOrder(expectedModifiedFilesContentsAfterRemount.OrderBy(x => x));
            }
        }
    

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

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

StreamReader.Read的代码示例4 - CanReadWriteAFileInParallel()

    using System.IO;

        [TestCaseSource(typeof(FileSystemRunner), nameof(FileSystemRunner.Runners))]
        [Order(3)]
        public void CanReadWriteAFileInParallel(FileSystemRunner fileSystem)
        {
            string fileName = @"CanReadWriteAFileInParallel";
            string virtualPath = this.Enlistment.GetVirtualPathTo(fileName);

            // Create the file new each time.
            virtualPath.ShouldNotExistOnDisk(fileSystem);
            File.Create(virtualPath).Dispose();

            bool keepRunning = true;
            Thread[] threads = new Thread[4];
            StringBuilder[] fileContents = new StringBuilder[4];

            // Writer
            fileContents[0] = new StringBuilder();
            threads[0] = new Thread(() =>
            {
                DateTime start = DateTime.Now;
                Random r = new Random(0); // Seeded for repeatability
                while ((DateTime.Now - start).TotalSeconds < 2.5)
                {
                    string newChar = r.Next(10).ToString();
                    fileSystem.AppendAllText(virtualPath, newChar);
                    fileContents[0].Append(newChar);
                    Thread.Yield();
                }

                keepRunning = false;
            });

            // Readers
            for (int i = 1; i < threads.Length; ++i)
            {
                int myIndex = i;
                fileContents[i] = new StringBuilder();
                threads[i] = new Thread(() =>
                {
                    using (Stream readStream = File.Open(virtualPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (StreamReader reader = new StreamReader(readStream, true))
                    {
                        while (keepRunning)
                        {
                            Thread.Yield();
                            fileContents[myIndex].Append(reader.ReadToEnd());
                        }

                        // Catch the last write that might have escaped us
                        fileContents[myIndex].Append(reader.ReadToEnd());
                    }
                });
            }

            foreach (Thread thread in threads)
            {
                thread.Start();
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            for (int i = 1; i < threads.Length; ++i)
            {
                fileContents[i].ToString().ShouldEqual(fileContents[0].ToString());
            }

            fileSystem.DeleteFile(virtualPath);
        }
    

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

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

StreamReader.Read的代码示例5 - ReadRegistry()

    using System.IO;

        public Dictionary ReadRegistry()
        {
            Dictionary allRepos = new Dictionary(GVFSPlatform.Instance.Constants.PathComparer);

            using (Stream stream = this.fileSystem.OpenFileStream(
                    Path.Combine(this.registryParentFolderPath, RegistryName),
                    FileMode.OpenOrCreate,
                    FileAccess.Read,
                    FileShare.Read,
                    callFlushFileBuffers: false))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string versionString = reader.ReadLine();
                    int version;
                    if (!int.TryParse(versionString, out version) ||
                        version > RegistryVersion)
                    {
                        if (versionString != null)
                        {
                            EventMetadata metadata = new EventMetadata();
                            metadata.Add("Area", EtwArea);
                            metadata.Add("OnDiskVersion", versionString);
                            metadata.Add("ExpectedVersion", versionString);
                            this.tracer.RelatedError(metadata, "ReadRegistry: Unsupported version");
                        }

                        return allRepos;
                    }

                    while (!reader.EndOfStream)
                    {
                        string entry = reader.ReadLine();
                        if (entry.Length > 0)
                        {
                            try
                            {
                                RepoRegistration registration = RepoRegistration.FromJson(entry);

                                string errorMessage;
                                string normalizedEnlistmentRootPath = registration.EnlistmentRoot;
                                if (this.fileSystem.TryGetNormalizedPath(registration.EnlistmentRoot, out normalizedEnlistmentRootPath, out errorMessage))
                                {
                                    if (!normalizedEnlistmentRootPath.Equals(registration.EnlistmentRoot, GVFSPlatform.Instance.Constants.PathComparison))
                                    {
                                        EventMetadata metadata = new EventMetadata();
                                        metadata.Add("registration.EnlistmentRoot", registration.EnlistmentRoot);
                                        metadata.Add(nameof(normalizedEnlistmentRootPath), normalizedEnlistmentRootPath);
                                        metadata.Add(TracingConstants.MessageKey.InfoMessage, $"{nameof(this.ReadRegistry)}: Mapping registered enlistment root to final path");
                                        this.tracer.RelatedEvent(EventLevel.Informational, $"{nameof(this.ReadRegistry)}_NormalizedPathMapping", metadata);
                                    }
                                }
                                else
                                {
                                    EventMetadata metadata = new EventMetadata();
                                    metadata.Add("registration.EnlistmentRoot", registration.EnlistmentRoot);
                                    metadata.Add("NormalizedEnlistmentRootPath", normalizedEnlistmentRootPath);
                                    metadata.Add("ErrorMessage", errorMessage);
                                    this.tracer.RelatedWarning(metadata, $"{nameof(this.ReadRegistry)}: Failed to get normalized path name for registed enlistment root");
                                }

                                if (normalizedEnlistmentRootPath != null)
                                {
                                    allRepos[normalizedEnlistmentRootPath] = registration;
                                }
                            }
                            catch (Exception e)
                            {
                                EventMetadata metadata = new EventMetadata();
                                metadata.Add("Area", EtwArea);
                                metadata.Add("entry", entry);
                                metadata.Add("Exception", e.ToString());
                                this.tracer.RelatedError(metadata, "ReadRegistry: Failed to read entry");
                            }
                        }
                    }
                }
            }

            return allRepos;
        }
    

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

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

StreamReader.Read的代码示例6 - OutputFileContents()

    using System.IO;

        public static void OutputFileContents(string filename, Action contentsValidator = null)
        {
            try
            {
                using (StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    Console.WriteLine("----- {0} -----", filename);

                    string contents = reader.ReadToEnd();

                    if (contentsValidator != null)
                    {
                        contentsValidator(contents);
                    }

                    Console.WriteLine(contents + "\n\n");
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine("Unable to read logfile at {0}: {1}", filename, ex.ToString());
            }
        }
    

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

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

StreamReader.Read的代码示例7 - Read_ReturnsReadStream()

    using System.IO;

        [Fact]
        public void Read_ReturnsReadStream()
        {
            // Arrange
            var fileInfo = new FileInfo(Path.Combine(TestFolder, "Home.cshtml"));
            var projectItem = new DefaultRazorProjectItem("/", "/Home.cshtml", "Home.cshtml", fileInfo);

            // Act
            var stream = projectItem.Read();

            // Assert
            Assert.Equal("home-content", new StreamReader(stream).ReadToEnd());
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:15,代码来源:DefaultRazorProjectItemTest.cs

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

StreamReader.Read的代码示例8 - WritePidFile_WorksAsExpected()

    using System.IO;
        [Fact]
        public void WritePidFile_WorksAsExpected()
        {
            // Arrange
            var expectedProcessId = Process.GetCurrentProcess().Id;
            var expectedRzcPath = typeof(ServerCommand).Assembly.Location;
            var expectedFileName = $"rzc-{expectedProcessId}";
            var directoryPath = Path.Combine(Path.GetTempPath(), "RazorTest", Guid.NewGuid().ToString());
            var path = Path.Combine(directoryPath, expectedFileName);

            var pipeName = Guid.NewGuid().ToString();
            var server = GetServerCommand(pipeName);

            // Act & Assert
            try
            {
                using (var _ = server.WritePidFile(directoryPath))
                {
                    Assert.True(File.Exists(path));

                    // Make sure another stream can be opened while the write stream is still open.
                    using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Write | FileShare.Delete))
                    using (var reader = new StreamReader(fileStream, Encoding.UTF8))
                    {
                        var lines = reader.ReadToEnd().Split(Environment.NewLine);
                        Assert.Equal(new[] { expectedProcessId.ToString(), "rzc", expectedRzcPath, pipeName }, lines);
                    }
                }

                // Make sure the file is deleted on dispose.
                Assert.False(File.Exists(path));
            }
            finally
            {
                // Cleanup after the test.
                if (Directory.Exists(directoryPath))
                {
                    Directory.Delete(directoryPath, recursive: true);
                }
            }
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:42,代码来源:ServerCommandTest.cs

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

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