C# StreamReader.ToString的代码示例

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

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


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

StreamReader.ToString的代码示例1 - TryLoadFromDisk()

    using System.IO;

        /// An optional callback to be run as soon as the fileLock is taken
        protected bool TryLoadFromDisk(
            TryParseAdd tryParseAdd,
            TryParseRemove tryParseRemove,
            Action add,
            out string error,
            Action synchronizedAction = null)
        {
            lock (this.fileLock)
            {
                try
                {
                    if (synchronizedAction != null)
                    {
                        synchronizedAction();
                    }

                    this.fileSystem.CreateDirectory(this.dataDirectoryPath);

                    this.OpenOrCreateDataFile(retryUntilSuccess: false);

                    if (this.collectionAppendsDirectlyToFile)
                    {
                        this.RemoveLastEntryIfInvalid();
                    }

                    long lineCount = 0;

                    this.dataFileHandle.Seek(0, SeekOrigin.Begin);
                    StreamReader reader = new StreamReader(this.dataFileHandle);
                    Dictionary parsedEntries = new Dictionary();
                    while (!reader.EndOfStream)
                    {
                        lineCount++;

                        // StreamReader strips the trailing /r/n
                        string line = reader.ReadLine();
                        if (line.StartsWith(RemoveEntryPrefix))
                        {
                            TKey key;
                            if (!tryParseRemove(line.Substring(RemoveEntryPrefix.Length), out key, out error))
                            {
                                error = string.Format("{0} is corrupt on line {1}: {2}", this.GetType().Name, lineCount, error);
                                return false;
                            }

                            parsedEntries.Remove(key);
                        }
                        else if (line.StartsWith(AddEntryPrefix))
                        {
                            TKey key;
                            TValue value;
                            if (!tryParseAdd(line.Substring(AddEntryPrefix.Length), out key, out value, out error))
                            {
                                error = string.Format("{0} is corrupt on line {1}: {2}", this.GetType().Name, lineCount, error);
                                return false;
                            }

                            parsedEntries[key] = value;
                        }
                        else
                        {
                            error = string.Format("{0} is corrupt on line {1}: Invalid Prefix '{2}'", this.GetType().Name, lineCount, line[0]);
                            return false;
                        }
                    }

                    foreach (KeyValuePair kvp in parsedEntries)
                    {
                        add(kvp.Key, kvp.Value);
                    }

                    if (!this.collectionAppendsDirectlyToFile)
                    {
                        this.CloseDataFile();
                    }
                }
                catch (IOException ex)
                {
                    error = ex.ToString();
                    this.CloseDataFile();
                    return false;
                }
                catch (Exception e)
                {
                    this.CloseDataFile();
                    throw new FileBasedCollectionException(e);
                }

                error = null;
                return true;
            }
        }
    

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

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

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

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

StreamReader.ToString的代码示例4 - TextEditorFromYaml()

    using System.IO;

        private void TextEditorFromYaml(object sender, EventArgs e)
        {
            string editorText = textEditor.GetText();
            if (editorText == string.Empty)
                return;

            try
            {
                if (FileFormat != null) {
                    if (IsXML)
                        FileFormat.BymlData = XmlByamlConverter.FromXML(textEditor.GetText());
                    else if (IsOldXML)
                    {
                        byte[] TextData = Encoding.Unicode.GetBytes(textEditor.GetText());
                        StreamReader t = new StreamReader(new MemoryStream(TextData), Encoding.GetEncoding(932));
                        FileFormat.BymlData = XmlConverter.ToByml(t.ReadToEnd());
                    }
                    else
                        FileFormat.BymlData = YamlByamlConverter.FromYaml(textEditor.GetText());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Byaml failed to convert! " + ex.ToString());
                return;
            }

            treeView1.Nodes.Clear();
            ParseBymlFirstNode();

            MessageBox.Show("Byaml converted successfully!");
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:34,代码来源:ByamlEditor.cs

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

StreamReader.ToString的代码示例5 - Load()

    using System.IO;

        #endregion

        public void Load(System.IO.Stream stream)
        {
            int offset = 0x14;
            offset = 0;

            if (!Directory.Exists($"{Runtime.ExecutableDir}/LUA"))
                Directory.CreateDirectory($"{Runtime.ExecutableDir}/LUA");

            string unluac = $"{Runtime.ExecutableDir}/LUA/unluac.jar";
            string target = $"{Runtime.ExecutableDir}/LUA/{FileName}.luac";

            new SubStream(stream, offset).ExportToFile(target);

            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = "java.exe";
            start.WorkingDirectory = $"{Runtime.ExecutableDir}/LUA";
            start.Arguments = $"-jar {unluac} {Utils.AddQuotesIfRequired(target)}";
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            start.CreateNoWindow = true;
            start.WindowStyle = ProcessWindowStyle.Hidden;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    try
                    {
                        Decompiled = reader.ReadToEnd();
                    }
                    catch (Exception ex)
                    {
                        Toolbox.Library.Forms.STErrorDialog.Show("Failed to decompile shader!", "Shader Tools", ex.ToString());
                        Decompiled = "";
                    }
                }
            }
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:41,代码来源:LUAC.cs

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

StreamReader.ToString的代码示例6 - DecompileShader()

    using System.IO;

        public static string DecompileShader(NswShaderType shaderType, byte[] Data, ulong Address = 0)
        {
            if (!Directory.Exists("temp"))
                Directory.CreateDirectory("temp");

            if (!Directory.Exists("ShaderTools"))
                Directory.CreateDirectory("ShaderTools");

            //     File.WriteAllBytes("temp/shader1.bin", Utils.CombineByteArray(data.ToArray()));
            File.WriteAllBytes("temp/shader1.bin", Data);

            if (!File.Exists($"{Runtime.ExecutableDir}/ShaderTools/Ryujinx.ShaderTools.exe"))
            {
                MessageBox.Show("No shader decompiler found in ShaderTools. If you want to decompile a shader, you can use Ryujinx's ShaderTools.exe and put in the ShaderTools folder of the toolbox.");
                return "";
            }

            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = "ShaderTools/Ryujinx.ShaderTools.exe";
            start.WorkingDirectory = Runtime.ExecutableDir;
            start.Arguments = $"{Utils.AddQuotesIfRequired("temp/shader1.bin")}";
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            start.CreateNoWindow = true;
            start.WindowStyle = ProcessWindowStyle.Hidden;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    try
                    {
                        return reader.ReadToEnd();
                    }
                    catch (Exception ex)
                    {
                        Toolbox.Library.Forms.STErrorDialog.Show("Failed to decompile shader!", "Shader Tools", ex.ToString());
                        return "";
                    }
                }
            }
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:43,代码来源:NSWShaderDecompile.cs

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

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

StreamReader.ToString的代码示例8 - ToTextAll()

    using System.IO;

        public static string ToTextAll(IEnumerable records, ChoCSVRecordConfiguration configuration = null, TraceSwitch traceSwitch = null)
            where TRec : class
        {
            if (records == null) return null;

            if (typeof(DataTable).IsAssignableFrom(typeof(TRec)))
            {
                StringBuilder csv = new StringBuilder();

                foreach (var dt in records.Take(1))
                {
                    configuration = configuration == null ? new ChoCSVRecordConfiguration().Configure(c => c.WithFirstLineHeader()) : configuration;
                    using (var w = new ChoCSVWriter(csv, configuration))
                        w.Write(dt);
                }

                return csv.ToString();
            }
            else if (typeof(IDataReader).IsAssignableFrom(typeof(TRec)))
            {
                StringBuilder csv = new StringBuilder();

                foreach (var dt in records.Take(1))
                {
                    configuration = configuration == null ? new ChoCSVRecordConfiguration().Configure(c => c.WithFirstLineHeader()) : configuration;
                    using (var w = new ChoCSVWriter(csv, configuration))
                        w.Write(dt);
                }

                return csv.ToString();
            }

            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            using (var parser = new ChoCSVWriter(writer, configuration) { TraceSwitch = traceSwitch == null ? ChoETLFramework.TraceSwitch : traceSwitch })
            {
                parser.Write(records);

                writer.Flush();
                stream.Position = 0;

                return reader.ReadToEnd();
            }
        }
    

开发者ID:Cinchoo,项目名称:ChoETL,代码行数:47,代码来源:ChoCSVWriter.cs

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

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