C# File.WriteAllText的代码示例

通过代码示例来学习C# File.WriteAllText方法

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


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

File.WriteAllText的代码示例1 - TryInitRepo()

    using System.IO;

        private Result TryInitRepo(ITracer tracer, GitRefs refs, Enlistment enlistmentToInit)
        {
            string repoPath = enlistmentToInit.WorkingDirectoryBackingRoot;
            GitProcess.Result initResult = GitProcess.Init(enlistmentToInit);
            if (initResult.ExitCodeIsFailure)
            {
                string error = string.Format("Could not init repo at to {0}: {1}", repoPath, initResult.Errors);
                tracer.RelatedError(error);
                return new Result(error);
            }

            GitProcess.Result remoteAddResult = new GitProcess(enlistmentToInit).RemoteAdd("origin", enlistmentToInit.RepoUrl);
            if (remoteAddResult.ExitCodeIsFailure)
            {
                string error = string.Format("Could not add remote to {0}: {1}", repoPath, remoteAddResult.Errors);
                tracer.RelatedError(error);
                return new Result(error);
            }

            File.WriteAllText(
                Path.Combine(repoPath, GVFSConstants.DotGit.PackedRefs),
                refs.ToPackedRefs());

            return new Result(true);
        }
    

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

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

File.WriteAllText的代码示例2 - Execute()

    using System.IO;

        public override bool Execute()
        {
            string templateFilePath = this.Template.ItemSpec;
            IDictionary properties = ParseProperties(this.Template.GetMetadata("Properties"));

            string outputFileDirectory = Path.GetDirectoryName(this.OutputFile);

            if (!File.Exists(templateFilePath))
            {
                this.Log.LogError("Failed to find template file '{0}'.", templateFilePath);
                return false;
            }

            // Copy the template to the destination to keep the same file mode bits/ACLs as the template
            File.Copy(templateFilePath, this.OutputFile, true);

            this.Log.LogMessage(MessageImportance.Low, "Reading template contents");
            string template = File.ReadAllText(this.OutputFile);

            this.Log.LogMessage(MessageImportance.Normal, "Compiling template '{0}'", templateFilePath);
            string compiled = Compile(template, properties);

            if (!Directory.Exists(outputFileDirectory))
            {
                this.Log.LogMessage(MessageImportance.Low, "Creating output directory '{0}'", outputFileDirectory);
                Directory.CreateDirectory(outputFileDirectory);
            }

            this.Log.LogMessage(MessageImportance.Normal, "Writing compiled template to '{0}'", this.OutputFile);
            File.WriteAllText(this.OutputFile, compiled);

            this.CompiledTemplate = new TaskItem(this.OutputFile, this.Template.CloneCustomMetadata());

            return true;
        }
    

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

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

File.WriteAllText的代码示例3 - SavePersistedValue()

    using System.IO;

        private static void SavePersistedValue(string dotGVFSRoot, string key, string value)
        {
            string metadataPath = Path.Combine(dotGVFSRoot, RepoMetadataName);

            Dictionary repoMetadata = new Dictionary();
            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));
                    repoMetadata.Add(kvp.Key, kvp.Value);
                }
            }

            repoMetadata[key] = value;

            string newRepoMetadataContents = string.Empty;

            foreach (KeyValuePair kvp in repoMetadata)
            {
                newRepoMetadataContents += "A " + JsonConvert.SerializeObject(kvp).Trim() + "\r\n";
            }

            File.WriteAllText(metadataPath, newRepoMetadataContents);
        }
    

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

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

File.WriteAllText的代码示例4 - OverwritingIndexShouldFail()

    using System.IO;

        private void OverwritingIndexShouldFail(string testFilePath)
        {
            string indexPath = this.Enlistment.GetVirtualPathTo(".git", "index");

            this.Enlistment.WaitForBackgroundOperations();
            byte[] indexContents = File.ReadAllBytes(indexPath);

            string testFileContents = "OverwriteIndexTest";
            this.fileSystem.WriteAllText(testFilePath, testFileContents);

            this.Enlistment.WaitForBackgroundOperations();

            this.RenameAndOverwrite(testFilePath, indexPath).ShouldBeFalse("GVFS should prevent renaming on top of index when GVFSLock is not held");
            byte[] newIndexContents = File.ReadAllBytes(indexPath);

            indexContents.SequenceEqual(newIndexContents).ShouldBeTrue("Index contenst should not have changed");

            this.fileSystem.DeleteFile(testFilePath);
        }
    

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

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

File.WriteAllText的代码示例5 - CheckEnableGitStatusCacheTokenFile()

    using System.IO;

        /// 
        /// To work around a behavior in ProjFS where notification masks on files that have been opened in virtualization instance are not invalidated
        /// when the virtualization instance is restarted, GVFS waits until after there has been a reboot before enabling the GitStatusCache.
        /// GVFS.Service signals that there has been a reboot since installing a version of GVFS that supports the GitStatusCache via
        /// the existence of the file "EnableGitStatusCacheToken.dat" in {CommonApplicationData}\GVFS\GVFS.Service
        /// (i.e. ProgramData\GVFS\GVFS.Service\EnableGitStatusCacheToken.dat on Windows).
        /// 
        private void CheckEnableGitStatusCacheTokenFile()
        {
            try
            {
                string statusCacheVersionTokenPath = Path.Combine(GVFSPlatform.Instance.GetSecureDataRootForGVFSComponent(GVFSConstants.Service.ServiceName), GVFSConstants.GitStatusCache.EnableGitStatusCacheTokenFile);
                if (File.Exists(statusCacheVersionTokenPath))
                {
                    this.tracer.RelatedInfo($"CheckEnableGitStatusCache: EnableGitStatusCacheToken file already exists at {statusCacheVersionTokenPath}.");
                    return;
                }

                DateTime lastRebootTime = NativeMethods.GetLastRebootTime();

                // GitStatusCache was included with GVFS on disk version 16. The 1st time GVFS that is at or above on disk version
                // is installed, it will write out a file indicating that the installation is "OnDiskVersion16Capable".
                // We can query the properties of this file to get the installation time, and compare this with the last reboot time for
                // this machine.
                string fileToCheck = Path.Combine(Configuration.AssemblyPath, GVFSConstants.InstallationCapabilityFiles.OnDiskVersion16CapableInstallation);

                if (File.Exists(fileToCheck))
                {
                    DateTime installTime = File.GetCreationTime(fileToCheck);
                    if (lastRebootTime > installTime)
                    {
                        this.tracer.RelatedInfo($"CheckEnableGitStatusCache: Writing out EnableGitStatusCacheToken file. GVFS installation time: {installTime}, last Reboot time: {lastRebootTime}.");
                        File.WriteAllText(statusCacheVersionTokenPath, string.Empty);
                    }
                    else
                    {
                        this.tracer.RelatedInfo($"CheckEnableGitStatusCache: Not writing EnableGitStatusCacheToken file - machine has not been rebooted since OnDiskVersion16Capable installation. GVFS installation time: {installTime}, last reboot time: {lastRebootTime}");
                    }
                }
                else
                {
                    this.tracer.RelatedError($"Unable to determine GVFS installation time: {fileToCheck} does not exist.");
                }
            }
            catch (Exception ex)
            {
                // Do not crash the service if there is an error here. Service is still healthy, but we
                // might not create file indicating that it is OK to use GitStatusCache.
                this.tracer.RelatedError($"{nameof(this.CheckEnableGitStatusCacheTokenFile)}: Unable to determine GVFS installation time or write EnableGitStatusCacheToken file due to exception. Exception: {ex.ToString()}");
            }
        }
    

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

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

File.WriteAllText的代码示例6 - Execute()

    using System.IO;

        public override bool Execute()
        {
            this.Log.LogMessage(MessageImportance.Normal,
                "Creating GVFS constants file with minimum Git version '{0}' at '{1}'...",
                this.MinimumGitVersion, this.OutputFile);

            if (!TryParseVersion(this.MinimumGitVersion, out var version))
            {
                this.Log.LogError("Failed to parse Git version '{0}'.", this.MinimumGitVersion);
                return false;
            }

            string outputDirectory = Path.GetDirectoryName(this.OutputFile);
            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            string template =
@"//
// This file is auto-generated by Scalar.Build.GenerateScalarConstants.
// Any changes made directly in this file will be lost.
//
using GVFS.Common.Git;

namespace GVFS.Common
{{
    public static partial class GVFSConstants
    {{
        public static readonly GitVersion SupportedGitVersion = new GitVersion({0}, {1}, {2}, ""{3}"", {4}, {5});
        public const string LibGit2LibraryName = ""{6}"";
    }}
}}";

            File.WriteAllText(
                this.OutputFile,
                string.Format(
                    template,
                    version.Major,
                    version.Minor,
                    version.Build,
                    version.Platform,
                    version.Revision,
                    version.MinorRevision,
                    this.LibGit2FileName));

            return true;
        }
    

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

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

File.WriteAllText的代码示例7 - Execute()

    using System.IO;

        public override bool Execute()
        {
            this.Log.LogMessage(MessageImportance.Normal,
                "Creating GVFS version header file with version '{0}' at '{1}'...",
                this.Version, this.OutputFile);

            string outputDirectory = Path.GetDirectoryName(this.OutputFile);
            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            string template =
@"/*
 * This file is auto-generated by GVFS.MSBuild.GenerateGVFSVersionHeader.
 * Any changes made directly in this file will be lost.
 */
#define GVFS_FILE_VERSION {1}
#define GVFS_FILE_VERSION_STRING ""{0}""
#define GVFS_PRODUCT_VERSION {1}
#define GVFS_PRODUCT_VERSION_STRING ""{0}""
";

            File.WriteAllText(
                this.OutputFile,
                string.Format(
                    template,
                    this.Version,
                    this.Version?.Replace('.',',')));

            return true;
        }
    

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

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

File.WriteAllText的代码示例8 - Execute()

    using System.IO;

        public override bool Execute()
        {
            this.Log.LogMessage(MessageImportance.Normal, "Creating application manifest file for '{0}'...", this.ApplicationName);

            string manifestDirectory = Path.GetDirectoryName(this.OutputFile);
            if (!Directory.Exists(manifestDirectory))
            {
                Directory.CreateDirectory(manifestDirectory);
            }

            // Any application that calls GetVersionEx must have an application manifest in order to get an accurate response.
            // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx for details
            File.WriteAllText(
                this.OutputFile,
                string.Format(
                    @"

  
  
    
      
      
    
  

",
                    this.Version,
                    this.ApplicationName));

            return true;
        }
    

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

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

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