C# 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

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

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

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

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

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

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

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

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

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

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

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

Directory.Move的代码示例7 - RenameFile()

    using System.IO;

        public void RenameFile(string source, string destination)
        {
            if (string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(destination))
                throw new Exception("Source / Destination file name cannot be null.");

            if (!_fileSystem.File.Exists(source))
                throw new SourceFileNotFoundException($"Source file was not found: {source}");

            try
            {
                if (_fileSystem.File.Exists(destination)) _fileSystem.File.Delete(destination);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (_fileSystem.Directory.Exists(_fileSystem.Path.GetDirectoryName(destination)))
                _fileSystem.File.Move(source, destination);
            else
                throw new DestinationPathNotFoundException(
                    $"Destination path was not found: {_fileSystem.Path.GetDirectoryName(destination)}");
        }
    

开发者ID:jwallet,项目名称:spy-spotify,代码行数:25,代码来源:FileManager.cs

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

Directory.Move的代码示例8 - UpdateDirectoryContent()

    using System.IO;

        private static void UpdateDirectoryContent()
        {
            try
            {
                Directory.Delete(UpdaterDirectoryPath, true);
                Directory.Move(UpdaterExtractedContentDirectoryPath, UpdaterDirectoryPath);
                Directory.Delete(UpdaterExtractedTempDirectoryPath);
            }
            catch
            {
                // ignored
            }
        }
    

开发者ID:jwallet,项目名称:spy-spotify,代码行数:15,代码来源:Updater.cs

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

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