C# Directory.Move的代码示例
Directory.Move方法的主要功能描述
通过代码示例来学习C# Directory.Move方法
通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。
Directory.Move是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的Directory.Move() 已经帮大家高亮显示了,大家可以重点学习Directory.Move() 方法的写法,从而快速掌握该方法的应用。
Directory.Move的代码示例1 - TryBackupFiles()
using System.IO;
private bool TryBackupFiles(ITracer tracer, GVFSEnlistment enlistment, string backupRoot)
{
string backupSrc = Path.Combine(backupRoot, "src");
string backupGit = Path.Combine(backupRoot, ".git");
string backupGvfs = Path.Combine(backupRoot, GVFSPlatform.Instance.Constants.DotGVFSRoot);
string backupDatabases = Path.Combine(backupGvfs, GVFSConstants.DotGVFS.Databases.Name);
string errorMessage = string.Empty;
if (!this.ShowStatusWhileRunning(
() =>
{
string ioError;
if (!this.TryIO(tracer, () => Directory.CreateDirectory(backupRoot), "Create backup directory", out ioError) ||
!this.TryIO(tracer, () => Directory.CreateDirectory(backupGit), "Create backup .git directory", out ioError) ||
!this.TryIO(tracer, () => Directory.CreateDirectory(backupGvfs), "Create backup .gvfs directory", out ioError) ||
!this.TryIO(tracer, () => Directory.CreateDirectory(backupDatabases), "Create backup .gvfs databases directory", out ioError))
{
errorMessage = "Failed to create backup folders at " + backupRoot + ": " + ioError;
return false;
}
// Move the current src folder to the backup location...
if (!this.TryIO(tracer, () => Directory.Move(enlistment.WorkingDirectoryBackingRoot, backupSrc), "Move the src folder", out ioError))
{
errorMessage = "Failed to move the src folder: " + ioError + Environment.NewLine;
errorMessage += "Make sure you have no open handles or running processes in the src folder";
return false;
}
// ... but move the .git folder back to the new src folder so we can preserve objects, refs, logs...
if (!this.TryIO(tracer, () => Directory.CreateDirectory(enlistment.WorkingDirectoryBackingRoot), "Create new src folder", out errorMessage) ||
!this.TryIO(tracer, () => Directory.Move(Path.Combine(backupSrc, ".git"), enlistment.DotGitRoot), "Keep existing .git folder", out errorMessage))
{
return false;
}
// ... backup the .gvfs hydration-related data structures...
string databasesFolder = Path.Combine(enlistment.DotGVFSRoot, GVFSConstants.DotGVFS.Databases.Name);
if (!this.TryBackupFilesInFolder(tracer, databasesFolder, backupDatabases, searchPattern: "*", filenamesToSkip: "RepoMetadata.dat"))
{
return false;
}
// ... backup everything related to the .git\index...
if (!this.TryIO(
tracer,
() => File.Move(
Path.Combine(enlistment.DotGitRoot, GVFSConstants.DotGit.IndexName),
Path.Combine(backupGit, GVFSConstants.DotGit.IndexName)),
"Backup the git index",
out errorMessage) ||
!this.TryIO(
tracer,
() => File.Move(
Path.Combine(enlistment.DotGVFSRoot, GitIndexProjection.ProjectionIndexBackupName),
Path.Combine(backupGvfs, GitIndexProjection.ProjectionIndexBackupName)),
"Backup GVFS_projection",
out errorMessage))
{
return false;
}
// ... backup all .git\*.lock files
if (!this.TryBackupFilesInFolder(tracer, enlistment.DotGitRoot, backupGit, searchPattern: "*.lock"))
{
return false;
}
return true;
},
"Backing up your files"))
{
this.Output.WriteLine();
this.WriteMessage(tracer, "ERROR: " + errorMessage);
return false;
}
return true;
}
开发者ID: microsoft, 项目名称: VFSForGit, 代码行数: 82, 代码来源: DehydrateVerb.cs
在microsoft提供的TryBackupFiles()方法中,该源代码示例一共有82行, 其中使用了Directory.Move()4次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Move()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Move()可能更有帮助。
Directory.Move的代码示例2 - TryRenameFolderForDelete()
using System.IO;
protected bool TryRenameFolderForDelete(ITracer tracer, string folderName, out string backupFolder)
{
backupFolder = folderName + ".deleteme";
tracer.RelatedInfo("Moving " + folderName + " to " + backupFolder);
try
{
Directory.Move(folderName, backupFolder);
}
catch (Exception e)
{
tracer.RelatedError("Failed to move {0} to {1}: {2}", folderName, backupFolder, e.ToString());
return false;
}
return true;
}
开发者ID: microsoft, 项目名称: VFSForGit, 代码行数: 20, 代码来源: DiskLayoutUpgrade.cs
在microsoft提供的TryRenameFolderForDelete()方法中,该源代码示例一共有20行, 其中使用了Directory.Move()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Move()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Move()可能更有帮助。
Directory.Move的代码示例3 - Install()
using System.IO;
static void Install()
{
Console.WriteLine("Installing...");
foreach (string dir in Directory.GetDirectories("master/"))
{
SetAccessRule(folderDir);
SetAccessRule(dir);
string dirName = new DirectoryInfo(dir).Name;
string destDir = Path.Combine(folderDir, dirName + @"\");
//Skip hash directory
if (dirName.Equals("Hashes", StringComparison.CurrentCultureIgnoreCase))
continue;
if (Directory.Exists(destDir))
{
Directory.Delete(destDir, true);
}
if (Directory.Exists(destDir))
Directory.Delete(destDir, true);
Directory.Move(dir, destDir);
}
foreach (string file in Directory.GetFiles("master/"))
{
if (file.Contains("Updater.exe") || file.Contains("Updater.exe.config")
|| file.Contains("Updater.pdb") || file.Contains("Octokit.dll"))
continue;
SetAccessRule(file);
SetAccessRule(folderDir);
string destFile = Path.Combine(folderDir, Path.GetFileName(file));
if (File.Exists(destFile))
File.Delete(destFile);
File.Move(file, destFile);
}
}
开发者ID: KillzXGaming, 项目名称: Switch-Toolbox, 代码行数: 42, 代码来源: Program.cs
在KillzXGaming提供的Install()方法中,该源代码示例一共有42行, 其中使用了Directory.Move()2次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Move()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Move()可能更有帮助。
Directory.Move的代码示例4 - GetExternalDictionaries()
using System.IO;
static byte[] GetExternalDictionaries()
{
byte[] dictionary = new byte[0];
var userDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SwitchToolbox");
if (!Directory.Exists(userDir))
Directory.CreateDirectory(userDir);
//Create folder for TOTK contents if it does not exist
if (!Directory.Exists(Path.Combine(userDir, "TOTK")))
Directory.CreateDirectory(Path.Combine(userDir, "TOTK"));
string folder = Path.Combine(userDir, "TOTK", "ZstdDictionaries");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
void TransferZDic(string path)
{
//Check if old directory contains the file and move it
string fileOld = Path.Combine(Runtime.ExecutableDir, "Lib", "ZstdDictionaries", path);
string fileNew = Path.Combine(folder, path);
if (!File.Exists(fileNew) && File.Exists(fileOld))
{
File.Move(fileOld, fileNew);
}
}
TransferZDic("bcett.byml.zsdic");
TransferZDic("pack.zsdic");
TransferZDic("zs.zsdic");
if (Directory.Exists(folder))
{
void CheckZDic(string fileName, string expectedExtension)
{
//Dictionary already set
if (dictionary.Length != 0) return;
string zDictPath = Path.Combine(folder, fileName);
//Then check if the input file uses the expected extension
if (File.Exists(zDictPath) && fileNameTemp.EndsWith(expectedExtension))
dictionary = File.ReadAllBytes(zDictPath);
}
//Order matters, zs must go last
CheckZDic("bcett.byml.zsdic", "bcett.byml.zs" );
CheckZDic("pack.zsdic", "pack.zs" );
CheckZDic("zs.zsdic", ".zs" );
}
return dictionary;
}
开发者ID: KillzXGaming, 项目名称: Switch-Toolbox, 代码行数: 53, 代码来源: Zstb.cs
在KillzXGaming提供的GetExternalDictionaries()方法中,该源代码示例一共有53行, 其中使用了Directory.Move()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Move()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Move()可能更有帮助。
Directory.Move的代码示例5 - UninstallPEComponents()
using System.IO;
///
/// Uninstalls unneeded Windows Components for Windows Setup Preinstallation-Environment
///
/// Path to the operating system
/// Callback to be notified of progress
public bool UninstallPEComponents(string ospath, ProgressCallback progressCallback)
{
List componentsNotInWinPE = GetRemovableREPackages(ospath);
//
// Backup Windows\Globalization\Sorting\SortDefault.nls
// Some builds have a composition issue leading to its removal when cleaning up components
//
string SortDefaultNlsPath = Path.Combine(ospath, "Windows", "Globalization", "Sorting", "SortDefault.nls");
string SortDefaultNlsBackup = Path.GetTempFileName();
if (File.Exists(SortDefaultNlsBackup))
{
File.Delete(SortDefaultNlsBackup);
}
File.Copy(SortDefaultNlsPath, SortDefaultNlsBackup);
//
// Initialize DISM log
//
string tempLog = Path.GetTempFileName();
DismApi.Initialize(DismLogLevel.LogErrorsWarningsInfo, tempLog);
DismSession session = DismApi.OpenOfflineSession(ospath);
DismPackageCollection packages = DismApi.GetPackages(session);
List componentsToRemove = new();
//
// Queue components we don't need according to our hardcoded list for removal
//
foreach (DismPackage package in packages)
{
if (componentsNotInWinPE.Any(x => package.PackageName.StartsWith(x, StringComparison.InvariantCultureIgnoreCase)))
{
componentsToRemove.Add(package);
}
}
//
// Remove components
//
foreach (DismPackage pkg in componentsToRemove)
{
try
{
void callback3(DismProgress progress)
{
progressCallback?.Invoke(false, (int)Math.Round((double)progress.Current / progress.Total * 100), "Removing " + pkg.PackageName);
}
DismApi.RemovePackageByName(session, pkg.PackageName, callback3);
}
catch //(Exception ex)
{
}
}
//
// Add back the file if it's now missing
//
if (!File.Exists(SortDefaultNlsPath))
{
string dir = Path.GetDirectoryName(SortDefaultNlsPath);
if (!Directory.Exists(dir))
{
_ = Directory.CreateDirectory(dir);
}
File.Move(SortDefaultNlsBackup, SortDefaultNlsPath);
}
//
// Clean DISM
//
try
{
DismApi.CloseSession(session);
}
catch { }
try
{
DismApi.Shutdown();
}
catch { }
try
{
File.Delete(tempLog);
}
catch { }
return true;
}
开发者ID: gus33000, 项目名称: UUPMediaCreator, 代码行数: 99, 代码来源: DismOperations.cs
在gus33000提供的UninstallPEComponents()方法中,该源代码示例一共有99行, 其中使用了Directory.Move()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Move()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Move()可能更有帮助。
Directory.Move的代码示例6 - ApplyAppxFixUpAsync()
using System.IO;
private static async Task ApplyAppxFixUpAsync(UpdateData update, string appxRoot, string cabsRoot)
{
if (string.IsNullOrWhiteSpace(cabsRoot))
{
cabsRoot = appxRoot;
}
Logging.Log($"Building appx license map from cabs...");
IDictionary appxLicenseFileMap = FeatureManifestService.GetAppxPackageLicenseFileMapFromCabs(Directory.GetFiles(cabsRoot, "*.cab", SearchOption.AllDirectories));
string[] appxFiles = Directory.GetFiles(Path.GetFullPath(appxRoot), "appx_*", SearchOption.TopDirectoryOnly);
// AppxPackage metadata was not deserialized from compdbs in the past, so
// this may trigger a retrieval of new compdbs from Microsoft
if (!update.CompDBs.Any(db => db.AppX != null))
{
Logging.Log($"Current replay is missing some appx package metadata. Re-downloading compdbs...");
update.CompDBs = await update.GetCompDBsAsync();
}
CompDB canonicalCompdb = update.CompDBs
.Where(compDB => compDB.Tags.Tag
.Find(x => x.Name
.Equals("UpdateType", StringComparison.InvariantCultureIgnoreCase))?.Value?
.Equals("Canonical", StringComparison.InvariantCultureIgnoreCase) == true)
.Where(x => x.AppX != null)
.FirstOrDefault();
if (canonicalCompdb != null)
{
foreach (string appxFile in appxFiles)
{
string payloadHash;
using (FileStream fileStream = File.OpenRead(appxFile))
{
using SHA256 sha = SHA256.Create();
payloadHash = Convert.ToBase64String(sha.ComputeHash(fileStream));
}
AppxPackage package = canonicalCompdb.AppX.AppXPackages.Package.Where(p => p.Payload.PayloadItem.FirstOrDefault().PayloadHash == payloadHash).FirstOrDefault();
if (package == null)
{
Logging.Log($"Could not locate package with payload hash {payloadHash}. Skipping.");
}
else
{
string appxFolder = Path.Combine(appxRoot, Path.GetDirectoryName(package.Payload.PayloadItem.FirstOrDefault().Path));
if (!Directory.Exists(appxFolder))
{
Logging.Log($"Creating {appxFolder}");
_ = Directory.CreateDirectory(appxFolder);
}
string appxPath = Path.Combine(appxRoot, package.Payload.PayloadItem.FirstOrDefault().Path);
Logging.Log($"Moving {appxFile} to {appxPath}");
File.Move(appxFile, appxPath, true);
}
}
foreach (AppxPackage package in canonicalCompdb.AppX.AppXPackages.Package)
{
if (package.LicenseData != null)
{
string appxFolder = Path.Combine(appxRoot, Path.GetDirectoryName(package.Payload.PayloadItem.FirstOrDefault().Path));
if (!Directory.Exists(appxFolder))
{
Logging.Log($"Creating {appxFolder}");
_ = Directory.CreateDirectory(appxFolder);
}
string appxPath = Path.Combine(appxRoot, package.Payload.PayloadItem.FirstOrDefault().Path);
string appxLicensePath = Path.Combine(appxFolder, $"{appxLicenseFileMap[Path.GetFileName(appxPath)]}");
Logging.Log($"Writing license to {appxLicensePath}");
File.WriteAllText(appxLicensePath, package.LicenseData);
}
}
}
Logging.Log($"Appx fixup applied.");
}
开发者ID: gus33000, 项目名称: UUPMediaCreator, 代码行数: 81, 代码来源: Process.cs
在gus33000提供的ApplyAppxFixUpAsync()方法中,该源代码示例一共有81行, 其中使用了Directory.Move()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Move()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Move()可能更有帮助。
Directory.Move()方法的常见问题及解答
C#中Directory.Move()的常见错误类型及注意事项
Directory.Move的错误类型有很多, 这里就不一一阐述了,本文只列出一些常见的代码示例供参考,大家可以看一下代码中Catch语句中是否有常见的错误捕获及处理。
C#中Directory.Move()的构造函数有哪些
Directory.Move构造函数功能基本类似,只是参数不同; 目前主流的集成开发环境都已经带智能提醒了,如:Visual Studio; 大家可以非常轻松的通过Visual Studio中的智能提醒,了解对应构造函数的用法。
如何使用ChartGPT写一段Directory.Move的代码
你可以在ChartGPT中输入如下的指令:"提供一个如何使用Directory.Move的C#代码示例"
ChartGPT写出的代码和本文中的小编提供的代码的区别。 ChartGPT发展到现在已经非常聪明了,但需要使用这提供非常专业的问题,才可能有比较好的源代码示例; 而本文中, 小编已经帮您列出来基本所有类和所有方法的使用示例, 而且这些示例基本都是一些网络大佬提供的源码,可以更方便的供一些开发菜鸟或者资深开发参考和学习。
Directory.Move所在的类及名称空间
Directory.Move是System.IO下的方法。
Directory.Move怎么使用?
Directory.Move使用上比较简单,可以参考MSDN中的帮助文档,也参考本文中提供的7个使用示例。
Directory.Move菜鸟教程
对于菜鸟来说,本文中提供的7个Directory.Move写法都将非常直观的帮您掌握Directory.Move的用法,是一个不错的参考教程。
本文中的Directory.Move方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。