简体   繁体   中英

Renaming copy of multiple files in C# in a uniform format

I'm working with C# in ASP.net framework. I need to make a copy of files and save them.

File.Copy("fileFirst.txt", "fileSecond.txt"); seems to work for that.

However I have multiple files and I need to do this for every single file. Instead of having to type the names for every single file how can I simply have a copy of the file such that it has the original filename with a -new appended on it's back.

Original file:      fileFirst.txt
Copy of the file:   fileFirst-new.txt

NOTE: It has to to do this for as many files as I have and not just one.

This code lists all the files in a directory and copies them to the same folder but with a different name.

    private static void RenameDirectoryFiles()
    {
        string pathfile = @"M:\_downloads\";

        string[] filePaths = Directory.GetFiles(pathfile);

        foreach (string filePath in filePaths)
        {
            try
            {
                string dire = Path.GetDirectoryName(filePath);
                string name = Path.GetFileNameWithoutExtension(filePath);
                string exte = Path.GetExtension(filePath);

                File.Copy($"{filePath}", $"{pathfile}\\{name}-New{exte}");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error File Copy");
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM