C# File.Move的代码示例

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

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


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

File.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()方法中,File的代码示例类中的Move的代码示例方法一共出现了4次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Move的代码示例2 - TryRenameToBackupFile()

    using System.IO;

        protected bool TryRenameToBackupFile(string filePath, out string backupPath, List messages)
        {
            backupPath = filePath + BackupExtension;
            try
            {
                File.Move(filePath, backupPath);
                this.Tracer.RelatedEvent(EventLevel.Informational, "FileMoved", new EventMetadata { { "SourcePath", filePath }, { "DestinationPath", backupPath } });
            }
            catch (Exception e)
            {
                messages.Add("Failed to back up " + filePath + " to " + backupPath);
                this.Tracer.RelatedError("Exception while moving " + filePath + " to " + backupPath + ": " + e.ToString());
                return false;
            }

            return true;
        }
    

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

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

File.Move的代码示例3 - EditInExternalProgram()

    using System.IO;
        private void EditInExternalProgram(bool UseDefaultEditor = true)
        {
            if (!ActiveTexture.CanEdit || !IsFinished)
                return;

            ImageProgramSettings settings = new ImageProgramSettings();
            settings.LoadImage(ActiveTexture);
            if (settings.ShowDialog() == DialogResult.OK)
            {
                UseDefaultEditor = !settings.OpenDefaultProgramSelection;

                string UseExtension = settings.GetSelectedExtension();
                FormatToChange = settings.GetSelectedImageFormat();

                string TemporaryName = Path.GetTempFileName();
                Utils.DeleteIfExists(Path.ChangeExtension(TemporaryName, UseExtension));
                File.Move(TemporaryName, Path.ChangeExtension(TemporaryName, UseExtension));
                TemporaryName = Path.ChangeExtension(TemporaryName, UseExtension);

                switch (UseExtension)
                {
                    case ".dds":
                        ActiveTexture.SaveDDS(TemporaryName, true, false, CurArrayDisplayLevel, CurMipDisplayLevel);
                        break;
                    case ".astc":
                        ActiveTexture.SaveASTC(TemporaryName, true, false, CurArrayDisplayLevel, CurMipDisplayLevel);
                        break;
                    case ".tga":
                        ActiveTexture.SaveTGA(TemporaryName, true, false, CurArrayDisplayLevel, CurMipDisplayLevel);
                        break;
                    default:
                        ActiveTexture.SaveBitMap(TemporaryName, true, false, CurArrayDisplayLevel, CurMipDisplayLevel);
                        break;
                }

                //Start watching for changes
                FileWatcher.EnableRaisingEvents = true;
                FileWatcher.Filter = Path.GetFileName(TemporaryName);

                if (UseDefaultEditor)
                    Process.Start(TemporaryName);
                else
                    ShowOpenWithDialog(TemporaryName);
            }
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:46,代码来源:ImageEditorBase.cs

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

File.Move的代码示例4 - 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()方法中,File的代码示例类中的Move的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Move的代码示例5 - SaveFileFormat()

    using System.IO;
        /// 
        /// Saves the  as a file from the given 
        /// 
        /// The format instance of the file being saved
        /// The name of the file
        /// The Alignment used for compression. Used for Yaz0 compression type. 
        /// Toggle for showing compression dialog
        /// 
        public static void SaveFileFormat(IFileFormat FileFormat, string FileName, bool EnableDialog = true, string DetailsLog = "")
        {
            //These always get created on loading a file,however not on creating a new file
            if (FileFormat.IFileInfo == null)
                throw new System.NotImplementedException("Make sure to impliment a IFileInfo instance if a format is being created!");

            Cursor.Current = Cursors.WaitCursor;
            FileFormat.FilePath = FileName;

            string compressionLog = "";
            if (FileFormat.IFileInfo.FileIsCompressed || FileFormat.IFileInfo.InArchive
                || Path.GetExtension(FileName) == ".szs" || Path.GetExtension(FileName) == ".sbfres"
                || Path.GetExtension(FileName) == ".mc")
            {
                //Todo find more optmial way to handle memory with files in archives
                //Also make compression require streams
                var mem = new System.IO.MemoryStream();
                FileFormat.Save(mem);
                mem =  new System.IO.MemoryStream(mem.ToArray());

                FileFormat.IFileInfo.DecompressedSize = (uint)mem.Length;

                var finalStream = CompressFileFormat(
                    FileFormat.IFileInfo.FileCompression,
                    mem,
                    FileFormat.IFileInfo.FileIsCompressed,
                    FileFormat.IFileInfo.Alignment,
                    FileName,
                    EnableDialog);

                compressionLog = finalStream.Item2;
                Stream compressionStream = finalStream.Item1;

                FileFormat.IFileInfo.CompressedSize = (uint)compressionStream.Length;
                compressionStream.ExportToFile(FileName);

                DetailsLog += "\n" + SatisfyFileTables(FileFormat, FileName, compressionStream,
                                    FileFormat.IFileInfo.DecompressedSize,
                                    FileFormat.IFileInfo.CompressedSize,
                                    FileFormat.IFileInfo.FileIsCompressed);

                compressionStream.Flush();
                compressionStream.Close();
            }
            else
            {
                //Check if a stream is active and the file is beinng saved to the same opened file
                if (FileFormat is ISaveOpenedFileStream && FileFormat.FilePath == FileName && File.Exists(FileName))
                {
                    string savedPath = Path.GetDirectoryName(FileName);
                    string tempPath = Path.Combine(savedPath, "tempST.bin");

                    //Save a temporary file first to not disturb the opened file
                    using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileFormat.Save(fileStream);
                        FileFormat.Unload();

                        //After saving is done remove the existing file
                        File.Delete(FileName);

                        //Now move and rename our temp file to the new file path
                        File.Move(tempPath, FileName);

                        FileFormat.Load(File.OpenRead(FileName));

                        var activeForm = LibraryGUI.GetActiveForm();
                        if (activeForm != null && activeForm is ObjectEditor)
                            ((ObjectEditor)activeForm).ReloadArchiveFile(FileFormat);
                    }
                }
                else
                {
                    using (var fileStream = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileFormat.Save(fileStream);
                    }
                }
            }

            if (EnableDialog)
            {
                if (compressionLog != string.Empty)
                    MessageBox.Show($"File has been saved to {FileName}. Compressed time: {compressionLog}", "Save Notification");
                else
                    MessageBox.Show($"File has been saved to {FileName}", "Save Notification");
            }

            //   STSaveLogDialog.Show($"File has been saved to {FileName}", "Save Notification", DetailsLog);
            Cursor.Current = Cursors.Default;
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:100,代码来源:STFileSaver.cs

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

File.Move的代码示例6 - 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()方法中,File的代码示例类中的Move的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Move的代码示例7 - MergeAll()

    using System.IO;
        public static void MergeAll(List Files, string output, ProgressLog Log)
        {
            int Check = Log.PushActivity("Gerber MergeAll");
            if (Files.Count > 1)
            {
                MultiMerge(Files[0], Files.Skip(1).ToList(), output, Log);
                Log.PopActivity(Check);
                return;
            }
            if (Files.Count < 2)
            {
                if (Files.Count == 1)
                {
                    Log.AddString("Merging 1 file is copying... doing so...");
                    if (File.Exists(output)) File.Delete(output);
                    File.Copy(Files[0], output);
                }
                else
                {
                    Log.AddString("Need files to do anything??");
                }
                Log.PopActivity(Check);
                return;
            }


            List TempFiles = new List();
            if (true)
            {

                List LeftOverFiles = new List();
                foreach (var a in Files)
                {
                    LeftOverFiles.Add(a);
                }

                while (LeftOverFiles.Count > 1)
                {
                    Log.AddString(String.Format("{0} files left in mergequeue", LeftOverFiles.Count));
                    string File1 = LeftOverFiles[0];
                    string File2 = LeftOverFiles[1];
                    LeftOverFiles.Remove(File1);
                    LeftOverFiles.Remove(File2);
                    string NewFile = Path.GetTempFileName();

                    Merge(File1, File2, NewFile, Log);
                    TempFiles.Add(NewFile);
                    LeftOverFiles.Add(NewFile);
                }

                if (File.Exists(output)) File.Delete(output);
                File.Move(LeftOverFiles[0], output);
            }
            else
            {

                string LastFile = Files[0];
                for (int i = 1; i < Files.Count - 1; i++)
                {
                    string NewFile = Path.GetTempFileName();
                    TempFiles.Add(NewFile);
                    Merge(LastFile, Files[i], NewFile, Log);
                    LastFile = NewFile;
                }
                if (File.Exists(output)) File.Delete(output);
                Merge(LastFile, Files.Last(), output, Log);
            }
            Log.AddString("Removing merge tempfiles");
            foreach (string s in TempFiles)
            {
                try
                {
                    File.Delete(s);
                }
                catch (Exception) { }
            }
            Log.PopActivity(Check);
        }
    

开发者ID:ThisIsNotRocketScience,项目名称:GerberTools,代码行数:79,代码来源:GerberMerger.cs

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

File.Move的代码示例8 - RazorGenerate_Rebuilds_IfInputFilesAreRenamed()

    using System.IO;

        [Fact]
        [InitializeTestProject("SimpleMvc")]
        public async Task RazorGenerate_Rebuilds_IfInputFilesAreRenamed()
        {
            // Act - 1
            var result = await DotnetMSBuild(RazorGenerateTarget);
            var file = Path.Combine(Project.DirectoryPath, "Views", "Home", "Index.cshtml");
            var renamed = Path.Combine(Project.DirectoryPath, "Views", "Home", "NewIndex.cshtml");
            var generated = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");

            // Assert - 1
            Assert.BuildPassed(result);
            Assert.FileExists(result, file);
            Assert.FileExists(result, generated);

            // Act - 2
            File.Move(file, renamed);
            result = await DotnetMSBuild(RazorGenerateTarget);

            // Assert - 2
            Assert.BuildPassed(result);
            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "NewIndex.cshtml.g.cs");
            Assert.FileDoesNotExist(result, generated);
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:26,代码来源:RazorGenerateIntegrationTest.cs

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

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