C# Directory.SetCurrentDirectory的代码示例
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
在ubisoft提供的Init()方法中,该源代码示例一共有57行, 其中使用了Directory.SetCurrentDirectory()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.SetCurrentDirectory()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.SetCurrentDirectory()可能更有帮助。
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
在EWSoftware提供的Execute()方法中,该源代码示例一共有72行, 其中使用了Directory.SetCurrentDirectory()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.SetCurrentDirectory()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.SetCurrentDirectory()可能更有帮助。
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
在EWSoftware提供的ApiFilterEditorDlg_Loaded()方法中,该源代码示例一共有100行, 其中使用了Directory.SetCurrentDirectory()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.SetCurrentDirectory()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.SetCurrentDirectory()可能更有帮助。
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
在EWSoftware提供的Execute()方法中,该源代码示例一共有17行, 其中使用了Directory.SetCurrentDirectory()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.SetCurrentDirectory()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.SetCurrentDirectory()可能更有帮助。
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
在EWSoftware提供的Execute()方法中,该源代码示例一共有96行, 其中使用了Directory.SetCurrentDirectory()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.SetCurrentDirectory()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.SetCurrentDirectory()可能更有帮助。
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
在EWSoftware提供的RemoveNode()方法中,该源代码示例一共有60行, 其中使用了Directory.SetCurrentDirectory()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.SetCurrentDirectory()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.SetCurrentDirectory()可能更有帮助。
Directory.SetCurrentDirectory()方法的常见问题及解答
C#中Directory.SetCurrentDirectory()的常见错误类型及注意事项
Directory.SetCurrentDirectory的错误类型有很多, 这里就不一一阐述了,本文只列出一些常见的代码示例供参考,大家可以看一下代码中Catch语句中是否有常见的错误捕获及处理。
C#中Directory.SetCurrentDirectory()的构造函数有哪些
Directory.SetCurrentDirectory构造函数功能基本类似,只是参数不同; 目前主流的集成开发环境都已经带智能提醒了,如:Visual Studio; 大家可以非常轻松的通过Visual Studio中的智能提醒,了解对应构造函数的用法。
如何使用ChartGPT写一段Directory.SetCurrentDirectory的代码
你可以在ChartGPT中输入如下的指令:"提供一个如何使用Directory.SetCurrentDirectory的C#代码示例"
ChartGPT写出的代码和本文中的小编提供的代码的区别。 ChartGPT发展到现在已经非常聪明了,但需要使用这提供非常专业的问题,才可能有比较好的源代码示例; 而本文中, 小编已经帮您列出来基本所有类和所有方法的使用示例, 而且这些示例基本都是一些网络大佬提供的源码,可以更方便的供一些开发菜鸟或者资深开发参考和学习。
Directory.SetCurrentDirectory所在的类及名称空间
Directory.SetCurrentDirectory是System.IO下的方法。
Directory.SetCurrentDirectory怎么使用?
Directory.SetCurrentDirectory使用上比较简单,可以参考MSDN中的帮助文档,也参考本文中提供的7个使用示例。
Directory.SetCurrentDirectory菜鸟教程
对于菜鸟来说,本文中提供的7个Directory.SetCurrentDirectory写法都将非常直观的帮您掌握Directory.SetCurrentDirectory的用法,是一个不错的参考教程。
本文中的Directory.SetCurrentDirectory方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。