Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用C重命名文件#_C#_File_Rename - Fatal编程技术网

C# 用C重命名文件#

C# 用C重命名文件#,c#,file,rename,C#,File,Rename,如何使用C#重命名文件?查看一下,将文件“移动”到一个新名称 System.IO.File.Move("oldfilename", "newfilename"); > > P>当C没有特征时,我使用C++或C:< /P> public partial class Program { [DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] public st

如何使用C#重命名文件?

查看一下,将文件“移动”到一个新名称

System.IO.File.Move("oldfilename", "newfilename");

>

> P>当C没有特征时,我使用C++或C:< /P>

public partial class Program
{
    [DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
    public static extern int rename(
            [MarshalAs(UnmanagedType.LPStr)]
            string oldpath,
            [MarshalAs(UnmanagedType.LPStr)]
            string newpath);

    static void FileRename()
    {
        while (true)
        {
            Console.Clear();
            Console.Write("Enter a folder name: ");
            string dir = Console.ReadLine().Trim('\\') + "\\";
            if (string.IsNullOrWhiteSpace(dir))
                break;
            if (!Directory.Exists(dir))
            {
                Console.WriteLine("{0} does not exist", dir);
                continue;
            }
            string[] files = Directory.GetFiles(dir, "*.mp3");

            for (int i = 0; i < files.Length; i++)
            {
                string oldName = Path.GetFileName(files[i]);
                int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
                if (pos == 0)
                    continue;

                string newName = oldName.Substring(pos);
                int res = rename(files[i], dir + newName);
            }
        }
        Console.WriteLine("\n\t\tPress any key to go to main menu\n");
        Console.ReadKey(true);
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchRenamer
{
    class Program
    {
        static void Main(string[] args)
        {
            var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");

            int i = 0;

            try
            {
                foreach (var dir in dirnames)
                {
                    var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);

                    DirectoryInfo d = new DirectoryInfo(dir);
                    FileInfo[] finfo = d.GetFiles("*.pdf");

                    foreach (var f in fnames)
                    {
                        i++;
                        Console.WriteLine("The number of the file being renamed is: {0}", i);

                        if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
                        {
                            File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
                        }
                        else
                        {
                            Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
                            foreach (FileInfo fi in finfo)
                            {
                                Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}
公共部分类程序
{
[DllImport(“msvcrt”,CallingConvention=CallingConvention.Cdecl,SetLastError=true)]
公共静态外部内部重命名(
[Marshallas(UnmanagedType.LPStr)]
字符串oldpath,
[Marshallas(UnmanagedType.LPStr)]
字符串newpath);
静态void FileRename()
{
while(true)
{
Console.Clear();
编写(“输入文件夹名称:”);
string dir=Console.ReadLine().Trim(“\\”)+“\\”;
if(string.IsNullOrWhiteSpace(dir))
打破
如果(!Directory.Exists(dir))
{
WriteLine(“{0}不存在”,dir);
继续;
}
string[]files=Directory.GetFiles(dir,*.mp3”);
for(int i=0;i
注意:在这个示例代码中,我们打开一个目录,搜索文件名中带有左括号和右括号的PDF文件。可以检查并替换名称中的任何字符,也可以使用替换函数指定一个全新的名称

从这段代码还有其他方法可以进行更精细的重命名,但我的主要目的是演示如何使用File.Move进行批量重命名。当我在笔记本电脑上运行它时,它对180个目录中的335个PDF文件有效。这是一时冲动的代码,有更详细的方法可以做到这一点

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchRenamer
{
    class Program
    {
        static void Main(string[] args)
        {
            var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");

            int i = 0;

            try
            {
                foreach (var dir in dirnames)
                {
                    var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);

                    DirectoryInfo d = new DirectoryInfo(dir);
                    FileInfo[] finfo = d.GetFiles("*.pdf");

                    foreach (var f in fnames)
                    {
                        i++;
                        Console.WriteLine("The number of the file being renamed is: {0}", i);

                        if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
                        {
                            File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
                        }
                        else
                        {
                            Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
                            foreach (FileInfo fi in finfo)
                            {
                                Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

在File.Move方法中,如果文件已经存在,则不会覆盖该文件。它将抛出一个异常

所以我们需要检查文件是否存在

/* Delete the file if exists, else no exception thrown. */

File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName
或者用try-catch环绕它以避免出现异常。

只需添加:

namespace System.IO
{
    public static class FileInfoExtensions
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, newName));
        }
    }
}
然后

FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
使用:

  • 第一种解决方案

    避免将
    System.IO.File.Move
    解决方案张贴在此处(包括带标记的答案)。 它通过网络发生故障。然而,复制/删除模式在本地和网络上工作。遵循其中一种移动解决方案,但将其替换为“复制”。然后使用File.Delete删除原始文件

    您可以创建一个重命名方法来简化它

  • 易用性

    在C#中使用VB程序集。 添加对Microsoft.VisualBasic的引用

    然后,要重命名该文件,请执行以下操作:

    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile,newName)

    两者都是字符串。请注意,myfile具有完整路径。newName没有。 例如:

    a = "C:\whatever\a.txt";
    b = "b.txt";
    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
    
    C:\which\
    文件夹现在将包含
    b.txt


  • 您可以将其复制为新文件,然后使用
    System.IO.file
    类删除旧文件:

    if (File.Exists(oldName))
    {
        File.Copy(oldName, newName, true);
        File.Delete(oldName);
    }
    
    Move正在执行相同的操作=复制并删除旧的

    使用:

    公共静态类FileInfoExtensions
    {
    /// 
    ///存在新文件名时的行为。
    /// 
    公共枚举文件ExistBehavior
    {
    /// 
    ///无:抛出IOException“目标文件已存在。”
    /// 
    无=0,
    /// 
    ///替换:替换目标中的文件。
    /// 
    替换=1,
    /// 
    ///跳过:跳过此文件。
    /// 
    跳过=2,
    /// 
    ///重命名:重命名文件(类似于窗口行为)
    /// 
    重命名=3
    }
    /// 
    ///重命名该文件。
    /// 
    ///目标文件。
    ///具有扩展名的新文件名。
    ///存在新文件名时的行为。
    公共静态无效重命名(this System.IO.FileInfo FileInfo,string newFileName,FileExistBehavior FileExistBehavior=FileExistBehavior.None)
    {
    字符串newFileNameWithoutExtension=System.IO.Path.GetFileNameWithoutExtension(newFileName);
    字符串newFileNameExtension=System.IO.Path.GetExtension(newFileName);
    字符串newFilePath=System.IO.Path.Combine(fileInfo.Directory.FullName,newFileName);
    if(System.IO.File.Exists(newFilePath))
    {
    开关(fileExistBehavior)
    {
    案例文件ExistBehavior。无:
    抛出新的System.IO.IOException(“目标文件已经存在。”);
    案例文件ExistBehavior。替换:
    System.IO.File.Delete(newFilePath);
    打破
    案例文件ExistBehavior。重命名:
    int duplicate_count=0;
    字符串newfilename和dupplicateindex;
    字符串newFilePathWithDupplicateIndex;
    做
    {
    双重计数++;
    newFileNameWithDupplicateIndex=newFileNameWithoutExtension+“(“+dupplicate\u count+”)”+newFileNameExtension;
    newFilePathWithDupplicateIndex=System.IO.Path.Combine(fileInfo.Directory.FullName,newFileNameWithDupplicateIndex);
    }
    而(System.IO.File.Exists(newFilePathWithDupplicateIndex));
    newFilePath=newFilePathWithDupplicateIndex;
    打破
    案例文件ExistBehavior.跳过:
    返回;
    }
    }
    System.IO.File.Move(fileInfo.FullName,newFilePath);
    }
    }
    
    如何使用此代码
    类程序
    {
    静态void Main(字符串[]参数)
    {
    字符串targetFile=System.IO.Path.Combine(@“D://test”,“New Tex
    
    if (File.Exists(oldName))
    {
        File.Copy(oldName, newName, true);
        File.Delete(oldName);
    }
    
    File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf", DateTime.Now));
    
    if (File.Exists(clogfile))
    {
        Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
        if (fileSizeInBytes > 5000000)
        {
            string path = Path.GetFullPath(clogfile);
            string filename = Path.GetFileNameWithoutExtension(clogfile);
            System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
        }
    }
    
    public void Rename(string filePath, string newFileName)
    {
        var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
        System.IO.File.Move(filePath, newFilePath);
    }
    
    public static class ImageRename
    {
        public static void ApplyChanges(string fileUrl,
                                        string temporaryImageName,
                                        string permanentImageName)
        {
            var currentFileName = Path.Combine(fileUrl,
                                               temporaryImageName);
    
            if (!File.Exists(currentFileName))
                throw new FileNotFoundException();
    
            var extention = Path.GetExtension(temporaryImageName);
            var newFileName = Path.Combine(fileUrl,
                                           $"{permanentImageName}
                                             {extention}");
    
            if (File.Exists(newFileName))
                File.Delete(newFileName);
    
            File.Move(currentFileName, newFileName);
        }
    }
    
    int rename(const char * oldname, const char * newname);
    
    using System.IO.Abstractions;
    
    IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
    fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));
    
    private static void Rename_File(string FileFullPath, string NewName) // nes name without directory actualy you can simply rename with fileinfo.MoveTo(Fullpathwithnameandextension);
            {
                FileInfo fileInfo = new FileInfo(FileFullPath);
                string DirectoryRoot = Directory.GetParent(FileFullPath).FullName;
    
                string filecreator = FileFullPath.Substring(DirectoryRoot.Length,FileFullPath.Length-DirectoryRoot.Length);
                 
                filecreator = DirectoryRoot + NewName;
                try
                {
                    fileInfo.MoveTo(filecreator);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(filecreator);
                    Console.WriteLine(ex.Message);
                    Console.ReadKey();
                }
    
        enter code here
                // string FileDirectory = Directory.GetDirectoryRoot()
    
            }