C# StreamWriter.Dispose的代码示例

通过代码示例来学习C# StreamWriter.Dispose方法

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


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

StreamWriter.Dispose的代码示例1 - RunCommandWithWaitAndStdIn()

    using System.IO;

        /// 
        /// Run the specified command as an external program. This method will return once the GVFSLock has been acquired.
        /// 
        /// The ID of the process that acquired the lock.
        ///  that can be signaled to exit the lock acquisition program.
        private static ManualResetEventSlim RunCommandWithWaitAndStdIn(
            GVFSFunctionalTestEnlistment enlistment,
            int resetTimeout,
            string pathToCommand,
            string args,
            string lockingProcessCommandName,
            string stdinToQuit,
            out int processId)
        {
            ManualResetEventSlim resetEvent = new ManualResetEventSlim(initialState: false);

            ProcessStartInfo processInfo = new ProcessStartInfo(pathToCommand);
            processInfo.WorkingDirectory = enlistment.RepoRoot;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardOutput = true;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardInput = true;
            processInfo.Arguments = args;

            Process holdingProcess = Process.Start(processInfo);
            StreamWriter stdin = holdingProcess.StandardInput;
            processId = holdingProcess.Id;

            enlistment.WaitForLock(lockingProcessCommandName);

            Task.Run(
                () =>
                {
                    resetEvent.Wait(resetTimeout);

                    try
                    {
                        // Make sure to let the holding process end.
                        if (stdin != null)
                        {
                            stdin.WriteLine(stdinToQuit);
                            stdin.Close();
                        }

                        if (holdingProcess != null)
                        {
                            bool holdingProcessHasExited = holdingProcess.WaitForExit(10000);

                            if (!holdingProcess.HasExited)
                            {
                                holdingProcess.Kill();
                            }

                            holdingProcess.Dispose();

                            holdingProcessHasExited.ShouldBeTrue("Locking process did not exit in time.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Assert.Fail($"{nameof(RunCommandWithWaitAndStdIn)} exception closing stdin {ex.ToString()}");
                    }
                    finally
                    {
                        resetEvent.Set();
                    }
                });

            return resetEvent;
        }
    

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

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

StreamWriter.Dispose的代码示例2 - RemoveTaggedLines()

    using System.IO;

        public void RemoveTaggedLines()
        {
            Flush();

            // Read and process the stream using spans to avoid any extra buffer copy.
            var removeLineBytes = _writer.Encoding.GetBytes(FileGeneratorUtilities.RemoveLineTag.ToCharArray()).AsSpan();
            var wholeStreamSpan = _stream.GetBuffer().AsSpan().Slice(0, (int)_stream.Length);
            if (wholeStreamSpan.IndexOf(removeLineBytes) == -1)
                return; // Early exit when there is no remove line tag in the file.

            var newLineBytes = _writer.Encoding.GetBytes(Environment.NewLine.ToCharArray()).AsSpan();
            var newStream = new MemoryStream((int)_stream.Length);
            int nextSlice = 0;
            while (true)
            {
                // Looking for end of line
                var restOfFileSlice = wholeStreamSpan.Slice(nextSlice);
                int endLineIndex = -1;
                int endLineMarkerSize = 0;
                for (int i = 0; i < restOfFileSlice.Length; i++)
                {
                    byte ch = restOfFileSlice[i];
                    if (ch == '\r' || ch == '\n')
                    {
                        endLineIndex = nextSlice + i;
                        endLineMarkerSize = 1;

                        if (ch == '\r' && i + 1 < restOfFileSlice.Length && restOfFileSlice[i + 1] == '\n')
                        {
                            endLineMarkerSize = 2;
                        }
                        break;
                    }
                }

                if (endLineIndex != -1)
                {
                    // Check if the line contains the remove line tag. Skip the line if found
                    var lineSlice = wholeStreamSpan.Slice(nextSlice, endLineIndex - nextSlice);
                    if (lineSlice.IndexOf(removeLineBytes) == -1)
                    {
                        newStream.Write(lineSlice);
                        newStream.Write(newLineBytes);
                    }

                    // Advance to next line
                    nextSlice += (lineSlice.Length + endLineMarkerSize);
                    if (nextSlice >= wholeStreamSpan.Length)
                    {
                        Debug.Assert(nextSlice == wholeStreamSpan.Length);
                        break;
                    }
                }
                else
                {
                    // Rest of file.
                    var lineSlice = wholeStreamSpan.Slice(nextSlice);

                    // Check if the line contains the remove line tag. Skip the line if found
                    if (lineSlice.IndexOf(removeLineBytes) == -1)
                    {
                        newStream.Write(lineSlice);
                        // Note: Adding a new line to generate the exact same thing than with original implementation
                        newStream.Write(newLineBytes);
                    }

                    // End of file
                    break;
                }
            }

            Debug.Assert(newStream.Length > 0);
            var newWriter = new StreamWriter(newStream, _writer.Encoding);
            _writer.Dispose(); // This will dispose _stream as well.

            _stream = newStream;
            _writer = newWriter;
        }
    

开发者ID:ubisoft,项目名称:Sharpmake,代码行数:80,代码来源:FileGenerator.cs

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

StreamWriter.Dispose的代码示例3 - Output()

    using System.IO;

        public override int Output(IEnumerable source, BsonValue options)
        {
            var filename = GetOption(options, "filename")?.AsString ?? throw new LiteException(0, "Collection $file_json requires string as 'filename' or a document field 'filename'");
            var overwritten = GetOption(options, "overwritten", false).AsBoolean;
            var encoding = GetOption(options, "encoding", "utf-8").AsString;
            var delimiter = GetOption(options, "delimiter", ",").AsString[0];
            var header = GetOption(options, "header", true).AsBoolean;

            var index = 0;

            IList headerFields = null;
            FileStream fs = null;
            StreamWriter writer = null;

            try
            {
                foreach (var doc in source)
                {
                    if (index++ == 0)
                    {
                        fs = new FileStream(filename, overwritten ? FileMode.OpenOrCreate : FileMode.CreateNew);
                        writer = new StreamWriter(fs, Encoding.GetEncoding(encoding));

                        headerFields = doc.Keys.ToList();

                        // print file header
                        if (header)
                        {
                            var idxHeader = 0;

                            foreach (var elem in doc)
                            {
                                if (idxHeader++ > 0) writer.Write(delimiter);
                                writer.Write(elem.Key);
                            }

                            writer.WriteLine();
                        }
                    }
                    else
                    {
                        writer.WriteLine();
                    }

                    var idxValue = 0;

                    foreach(var field in headerFields)
                    {
                        var value = doc[field];

                        if (idxValue++ > 0) writer.Write(delimiter);

                        this.WriteValue(value, writer);
                    }
                }

                if (index > 0)
                {
                    writer.Flush();
                }
            }
            finally
            {
                if (writer != null) writer.Dispose();
                if (fs != null) fs.Dispose();
            }

            return index;
        }
    

开发者ID:mbdavid,项目名称:LiteDB,代码行数:71,代码来源:SysFileCsv.cs

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

StreamWriter.Dispose的代码示例4 - Output()

    using System.IO;

        public override int Output(IEnumerable source, BsonValue options)
        {
            var filename = GetOption(options, "filename")?.AsString ?? throw new LiteException(0, "Collection $file_json requires string as filename or a document field 'filename'");
            var pretty = GetOption(options, "pretty", false).AsBoolean;
            var indent = GetOption(options, "indent", 4).AsInt32;
            var encoding = GetOption(options, "encoding", "utf-8").AsString;
            var overwritten = GetOption(options, "overwritten", false).AsBoolean;

            var index = 0;
            FileStream fs = null;
            StreamWriter writer = null;
            JsonWriter json = null;

            try
            {
                foreach (var doc in source)
                {
                    if (index++ == 0)
                    {
                        fs = new FileStream(filename, overwritten ? FileMode.OpenOrCreate : FileMode.CreateNew);
                        writer = new StreamWriter(fs, Encoding.GetEncoding(encoding));
                        json = new JsonWriter(writer)
                        {
                            Pretty = pretty,
                            Indent = indent
                        };

                        writer.WriteLine("[");
                    }
                    else
                    {
                        writer.WriteLine(",");
                    }

                    json.Serialize(doc);
                }

                if (index > 0)
                {
                    writer.WriteLine();
                    writer.Write("]");
                    writer.Flush();
                }
            }
            finally
            {
                if (writer != null) writer.Dispose();
                if (fs != null) fs.Dispose();
            }

            return index;
        }
    

开发者ID:mbdavid,项目名称:LiteDB,代码行数:54,代码来源:SysFileJson.cs

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

StreamWriter.Dispose的代码示例5 - CreateScriptableObjectClassScript()

    using System.IO;

        /// 
        /// Create a ScriptableObject class and write it down on the specified folder.
        /// 
        protected void CreateScriptableObjectClassScript(BaseMachine machine, ScriptPrescription sp)
        {
            sp.className = machine.WorkSheetName;
            sp.dataClassName = machine.WorkSheetName + "Data";
            sp.template = GetTemplate("ScriptableObjectClass");

            // check the directory path exists
            string fullPath = TargetPathForClassScript(machine.WorkSheetName);
            string folderPath = Path.GetDirectoryName(fullPath);
            if (!Directory.Exists(folderPath))
            {
                EditorUtility.DisplayDialog(
                    "Warning",
                    "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.",
                    "OK"
                );
                return;
            }

            StreamWriter writer = null;
            try
            {
                // write a script to the given folder.		
                writer = new StreamWriter(fullPath);
                writer.Write(new ScriptGenerator(sp).ToString());
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.Message);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
            }
        }
    

开发者ID:kimsama,项目名称:Unity-QuickSheet,代码行数:44,代码来源:BaseMachineEditor.cs

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

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