C# Directory.SetCurrentDirectory的代码示例

通过代码示例来学习C# Directory.SetCurrentDirectory方法

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


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

Directory.SetCurrentDirectory的代码示例1 - Init()

    using System.IO;

        protected void Init()
        {
            bool debugLog = true;
            bool multithreaded = false;
            bool writeFiles = false;
            bool dumpDependency = true;

            DependencyTracker.ResetSingleton();
            DependencyTracker.GraphWriteLegend = false;

            Builder = new Builder(
                new BuildContext.GenerateAll(debugLog, writeFiles),
                multithreaded,
                dumpDependency,
                false,
                false,
                false,
                false,
                true,
                GetGeneratorsManager,
                null
            );

            Builder.Arguments.ConfigureOrder = _configureOrder;

            // Force the test to load and register CommonPlatforms.dll as a Sharpmake extension
            // because sometimes you get the "no implementation of XX for platform YY."
            switch (_initType)
            {
                case InitType.Cpp:
                    {
                        // HACK: Explicitly reference something from CommonPlatforms to get
                        // visual studio to load the assembly
                        var platformWin64Type = typeof(Windows.Win64Platform);
                        PlatformRegistry.RegisterExtensionAssembly(platformWin64Type.Assembly);
                    }
                    break;
                case InitType.CSharp:
                    {
                        var platformDotNetType = typeof(DotNetPlatform);
                        PlatformRegistry.RegisterExtensionAssembly(platformDotNetType.Assembly);
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(_initType), _initType, null);
            }

            Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory);

            // Allow message log from builder.
            Builder.EventOutputError += (message, args) => { ++ErrorCount; Util.LogWrite(message, args); };
            Builder.EventOutputWarning += (message, args) => { ++WarningCount; Util.LogWrite(message, args); };
            Builder.EventOutputMessage += Util.LogWrite;
            Builder.EventOutputDebug += Util.LogWrite;
        }
    

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

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

Directory.SetCurrentDirectory的代码示例2 - Execute()

    using System.IO;

        /// 
        /// This method is used to execute the plug-in during the build process
        /// 
        /// The current execution context
        public void Execute(ExecutionContext context)
        {
            if(context == null)
                throw new ArgumentNullException(nameof(context));

            if(context.BuildStep == BuildStep.GenerateNamespaceSummaries)
            {
                // Merge the additional reference links information
                builder.ReportProgress("Performing partial builds on additional targets' projects");

                // Build each of the projects
                foreach(ReferenceLinkSettings vs in otherLinks)
                {
                    using(SandcastleProject project = new SandcastleProject(vs.HelpFileProject, true, true))
                    {
                        // We'll use a working folder below the current project's working folder
                        string workingPath = Path.Combine(builder.WorkingFolder,
                            vs.HelpFileProject.GetHashCode().ToString("X", CultureInfo.InvariantCulture));

                        bool success = this.BuildProject(project, workingPath);

                        // Switch back to the original folder for the current project
                        Directory.SetCurrentDirectory(builder.ProjectFolder);

                        if(!success)
                        {
                            throw new BuilderException("ARL0003", "Unable to build additional target project: " +
                                project.Filename);
                        }

                        // Save the reflection file location as we need it later
                        vs.ReflectionFilename = Path.Combine(workingPath, "reflection.xml");
                    }
                }

                return;
            }

            if(context.BuildStep == BuildStep.GenerateInheritedDocumentation)
            {
                this.MergeInheritedDocConfig();
                return;
            }

            if(context.BuildStep == BuildStep.CreateBuildAssemblerConfigs)
            {
                builder.ReportProgress("Adding additional reference link namespaces...");

                var rn = builder.ReferencedNamespaces;

                HashSet validNamespaces = new HashSet(Directory.EnumerateFiles(
                    builder.FrameworkReflectionDataFolder, "*.xml", SearchOption.AllDirectories).Select(
                        f => Path.GetFileNameWithoutExtension(f)));

                foreach(ReferenceLinkSettings vs in otherLinks)
                    if(!String.IsNullOrEmpty(vs.ReflectionFilename))
                        foreach(var n in BuildProcess.GetReferencedNamespaces(vs.ReflectionFilename, validNamespaces))
                            rn.Add(n);

                return;
            }

            // Merge the reflection file info into sancastle.config
            if(File.Exists(builder.BuildAssemblerConfigurationFile))
                this.MergeReflectionInfo();
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:72,代码来源:AdditionalReferenceLinksPlugIn.cs

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

Directory.SetCurrentDirectory的代码示例3 - ApiFilterEditorDlg_Loaded()

    using System.IO;
        #endregion

        #region Event handlers
        //=====================================================================

        /// 
        /// This is used to start the background build process from which we will get the information to load the
        /// tree view.
        /// 
        /// The sender of the event
        /// The event arguments
        private async void ApiFilterEditorDlg_Loaded(object sender, RoutedEventArgs e)
        {
            string tempPath;

            tvApiList.IsEnabled = grdSearchOptions.IsEnabled = btnReset.IsEnabled = false;
            txtSearchText.Text = "Loading...";

            try
            {
                // Clone the project for the build and adjust its properties for our needs.  Build output is
                // stored in a temporary folder and it keeps the intermediate files.
                tempPath = Path.GetTempFileName();

                File.Delete(tempPath);
                tempPath = Path.Combine(Path.GetDirectoryName(tempPath), "SHFBPartialBuild");

                if(!Directory.Exists(tempPath))
                    Directory.CreateDirectory(tempPath);

                tempProject = new SandcastleProject(apiFilter.Project.MSBuildProject)
                {
                    CleanIntermediates = false,
                    OutputPath = tempPath
                };

                cancellationTokenSource = new CancellationTokenSource();

                buildProcess = new BuildProcess(tempProject, PartialBuildType.GenerateReflectionInfo)
                {
                    ProgressReportProvider = new Progress(buildProcess_ReportProgress),
                    CancellationToken = cancellationTokenSource.Token,
                    SuppressApiFilter = true        // We must suppress the current API filter for this build
                };

                var apiNodes = await Task.Run(() => this.BuildProject(), cancellationTokenSource.Token).ConfigureAwait(true);

                if(!cancellationTokenSource.IsCancellationRequested)
                {
                    if(buildProcess.CurrentBuildStep == BuildStep.Completed)
                    {
                        tvApiList.ItemsSource = apiNodes;
                        tvApiList.IsEnabled = grdSearchOptions.IsEnabled = btnReset.IsEnabled = true;
                    }
                    else
                        MessageBox.Show("Unable to build project to obtain API information.  Please perform a " +
                            "normal build to identify and correct the problem.", Constants.AppName,
                            MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                    this.Close();
            }
            catch(OperationCanceledException )
            {
                // Just close if canceled while loading the filter info after the build
                this.Close();
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());

                MessageBox.Show("Unable to build project to obtain API information.  Error: " +
                    ex.Message, Constants.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                buildProcess = null;

                try
                {
                    // Restore the current project's base path
                    Directory.SetCurrentDirectory(Path.GetDirectoryName(apiFilter.Project.Filename));
                }
                catch(Exception ex)
                {
                    // Ignore any exceptions
                    System.Diagnostics.Debug.WriteLine(ex);
                }

                if(cancellationTokenSource != null)
                {
                    cancellationTokenSource.Dispose();
                    cancellationTokenSource = null;
                }

                grdProgress.Visibility = Visibility.Hidden;
                txtSearchText.Text = null;
            }
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:100,代码来源:ApiFilterEditorDlg.xaml.cs

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

Directory.SetCurrentDirectory的代码示例4 - Execute()

    using System.IO;

        /// 
        /// This is overridden to set the working folder before executing the task and to invert the result
        /// returned from the help compiler.
        /// 
        /// True if successful or false on failure
        public override bool Execute()
        {
            Directory.SetCurrentDirectory(this.WorkingFolder);

            // HHC is backwards and returns zero on failure and non-zero on success
            if(base.Execute() && this.ExitCode == 0 && String.IsNullOrEmpty(this.LocalizeApp))
                return base.HandleTaskExecutionErrors();

            return true;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:17,代码来源:Build1xHelpFile.cs

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

Directory.SetCurrentDirectory的代码示例5 - Execute()

    using System.IO;

        #endregion

        #region Execute method
        //=====================================================================

        /// 
        /// This is used to execute the task and clean the output folder
        /// 
        /// True on success or false on failure.
        public override bool Execute()
        {
            string projectPath;

            try
            {
                projectPath = Path.GetDirectoryName(Path.GetFullPath(this.ProjectFile));

                // Make sure we start out in the project's output folder
                // in case the output folder is relative to it.
                Directory.SetCurrentDirectory(Path.GetDirectoryName(Path.GetFullPath(projectPath)));

                // Clean the working folder
                if(!String.IsNullOrEmpty(this.WorkingPath))
                {
                    if(!Path.IsPathRooted(this.WorkingPath))
                        this.WorkingPath = Path.GetFullPath(Path.Combine(projectPath, this.WorkingPath));

                    if(Directory.Exists(this.WorkingPath))
                    {
                        BuildProcess.VerifySafePath(nameof(WorkingPath), this.WorkingPath, projectPath);
                        Log.LogMessage(MessageImportance.High, "Removing working folder...");
                        Directory.Delete(this.WorkingPath, true);
                    }
                }

                if(!Path.IsPathRooted(this.OutputPath))
                    this.OutputPath = Path.GetFullPath(Path.Combine(projectPath, this.OutputPath));

                if(Directory.Exists(this.OutputPath))
                {
                    Log.LogMessage(MessageImportance.High, "Removing build files...");
                    BuildProcess.VerifySafePath(nameof(OutputPath), this.OutputPath, projectPath);

                    // Read-only and/or hidden files and folders are ignored as they are assumed to be
                    // under source control.
                    foreach(string file in Directory.EnumerateFiles(this.OutputPath))
                        if((File.GetAttributes(file) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0)
                            File.Delete(file);
                        else
                            Log.LogMessage(MessageImportance.High, "Skipping read-only or hidden file '{0}'", file);

                    Log.LogMessage(MessageImportance.High, "Removing build folders...");

                    foreach(string folder in Directory.EnumerateDirectories(this.OutputPath))
                        try
                        {
                            // Some source control providers have a mix of read-only/hidden files within a folder
                            // that isn't read-only/hidden (i.e. Subversion).  In such cases, leave the folder alone.
                            if(Directory.EnumerateFileSystemEntries(folder, "*", SearchOption.AllDirectories).Any(f =>
                              (File.GetAttributes(f) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) != 0))
                                Log.LogMessage(MessageImportance.High, "Skipping folder '{0}' as it contains read-only or hidden folders/files", folder);
                            else
                                if((File.GetAttributes(folder) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0)
                                    Directory.Delete(folder, true);
                                else
                                    Log.LogMessage(MessageImportance.High, "Skipping folder '{0}' as it is read-only or hidden", folder);
                        }
                        catch(IOException ioEx)
                        {
                            Log.LogMessage(MessageImportance.High, "Did not delete folder '{0}': {1}", folder, ioEx.Message);
                        }
                        catch(UnauthorizedAccessException uaEx)
                        {
                            Log.LogMessage(MessageImportance.High, "Did not delete folder '{0}': {1}", folder, uaEx.Message);
                        }

                    // Delete the log file too if it exists
                    if(!String.IsNullOrEmpty(this.LogFileLocation) && File.Exists(this.LogFileLocation))
                    {
                        Log.LogMessage(MessageImportance.High, "Removing build log...");
                        File.Delete(this.LogFileLocation);
                    }
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                Log.LogError(null, "CT0001", "CT0001", "SHFB", 0, 0, 0, 0,
                    "Unable to clean output folder.  Reason: {0}", ex);
                return false;
            }

            return true;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:96,代码来源:CleanHelp.cs

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

Directory.SetCurrentDirectory的代码示例6 - RemoveNode()

    using System.IO;

        /// 
        /// Remove the children of a folder node from the project
        /// 
        /// The parent folder node
        /// True to delete the items or false to just remove them from the project
        public void RemoveNode(TreeNode node, bool permanently)
        {
            NodeData nodeData;
            FileItem fileItem;
            TreeNode[] children;
            string projectFolder;

            if(node == null)
                throw new ArgumentNullException(nameof(node));

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                treeView.SuspendLayout();

                // Remove any children
                if(node.Nodes.Count > 0)
                {
                    children = new TreeNode[node.Nodes.Count];
                    node.Nodes.CopyTo(children, 0);

                    foreach(TreeNode n in children)
                        this.RemoveNode(n, permanently);
                }

                // Remove the node itself
                nodeData = (NodeData)node.Tag;
                fileItem = (FileItem)nodeData.Item;
                projectFolder = Path.GetDirectoryName(fileItem.Project.Filename);
                fileItem.RemoveFromProjectFile();
                node.Remove();

                if(permanently)
                    if(fileItem.BuildAction == BuildAction.Folder)
                    {
                        // If in or below the folder to remove, get out of it
                        if(FolderPath.TerminatePath(Directory.GetCurrentDirectory()).StartsWith(
                          fileItem.IncludePath, StringComparison.OrdinalIgnoreCase))
                            Directory.SetCurrentDirectory(projectFolder);

                        if(Directory.Exists(fileItem.IncludePath))
                            Directory.Delete(fileItem.IncludePath, true);
                    }
                    else
                        if(File.Exists(fileItem.IncludePath))
                            File.Delete(fileItem.IncludePath);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                treeView.ResumeLayout();
            }
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:60,代码来源:FileTree.cs

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

Directory.SetCurrentDirectory的代码示例7 - Execute()

    using System.IO;
        #endregion

        #region Task execution
        //=====================================================================

        /// 
        /// This executes the task
        /// 
        /// True on success, false on failure
        public override bool Execute()
        {
            string currentDirectory = null;
            bool success = false;
#if DEBUG
            if(this.WaitForDebugger)
            {
                while(!Debugger.IsAttached && !waitCancelled)
                {
                    this.Log.LogMessage("DEBUG MODE: Waiting for debugger to attach (process ID: {0})",
                        Process.GetCurrentProcess().Id);
                    System.Threading.Thread.Sleep(1000);
                }

                if(waitCancelled)
                    return false;

                Debugger.Break();
            }
#endif
            Assembly application = Assembly.GetCallingAssembly();
            System.Reflection.AssemblyName applicationData = application.GetName();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(application.Location);

            this.Log.LogMessage("{0} (v{1})", applicationData.Name, fvi.ProductVersion);

            var copyrightAttributes = application.GetCustomAttributes();

            foreach(AssemblyCopyrightAttribute copyrightAttribute in copyrightAttributes)
                this.Log.LogMessage(copyrightAttribute.Copyright);

            if(this.Assemblies == null || this.Assemblies.Length == 0)
            {
                this.WriteMessage(MessageLevel.Error, "At least one assembly (.dll or .exe) is " +
                    "required for MRefBuilder to parse");
                return false;
            }

            try
            {
                // Switch to the working folder for the build so that relative paths are resolved properly
                if(!String.IsNullOrWhiteSpace(this.WorkingFolder))
                {
                    currentDirectory = Directory.GetCurrentDirectory();
                    Directory.SetCurrentDirectory(Path.GetFullPath(this.WorkingFolder));
                }

                success = this.GenerateReflectionInformation();
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                this.WriteMessage(MessageLevel.Error, "An unexpected error occurred trying to " +
                    "execute the MRefBuilder MSBuild task: {0}", ex);
            }
            finally
            {
                if(currentDirectory != null)
                    Directory.SetCurrentDirectory(currentDirectory);
            }

            return success;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:73,代码来源:MRefBuilder.cs

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

Directory.SetCurrentDirectory的代码示例8 - miViewBuiltHelpFile_Click()

    using System.IO;

        /// 
        /// View the last build help output
        /// 
        /// The sender of the event
        /// The event arguments
        private void miViewBuiltHelpFile_Click(object sender, EventArgs e)
        {
            // Make sure we start out in the project's output folder in case the output folder is relative to it
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Path.GetFullPath(project.Filename)));

            string outputPath = project.OutputPath;

            // If the output path contains MSBuild variables, get the evaluated value from the project
            if(outputPath.IndexOf("$(", StringComparison.Ordinal) != -1)
                outputPath = project.MSBuildProject.GetProperty("OutputPath").EvaluatedValue;

            if(String.IsNullOrEmpty(outputPath))
                outputPath = Directory.GetCurrentDirectory();
            else
                outputPath = Path.GetFullPath(outputPath);

            if(sender == miViewHtmlHelp1)
                outputPath += project.HtmlHelpName + ".chm";
            else
                if(sender == miViewOpenXml)
                    outputPath += project.HtmlHelpName + ".docx";
                else
                    if(sender == miViewHelpFile)
                        outputPath += "_Sidebar.md";
                    else
                        outputPath += "Index.html";

            // If there are substitution tags present, have a go at resolving them
            if(outputPath.IndexOf("{@", StringComparison.Ordinal) != -1)
            {
                try
                {
                    var bp = new BuildProcess(project);
                    outputPath = bp.SubstitutionTags.TransformText(outputPath);
                }
                catch
                {
                    // Ignore errors
                    MessageBox.Show("The help filename appears to contain substitution tags but they could " +
                        "not be resolved to determine the actual file to open for viewing.  Building " +
                        "website output and viewing it can be used to work around this issue.",
                        Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            if(!File.Exists(outputPath))
            {
                MessageBox.Show("A copy of the help file does not appear to exist yet.  It may need to be built.",
                    Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                Process.Start(outputPath);
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                MessageBox.Show(String.Format(CultureInfo.CurrentCulture, "Unable to open help file '{0}'\r\nReason: {1}",
                    outputPath, ex.Message), Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:71,代码来源:MainForm.cs

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

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