your programing

C #에서 파일 이름 바꾸기

lovepro 2020. 10. 3. 11:26
반응형

C #에서 파일 이름 바꾸기


C #을 사용하여 파일 이름을 바꾸려면 어떻게합니까?


System.IO.File.Move를 살펴보고 파일을 새 이름으로 "이동"하십시오.

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

System.IO.File.Move(oldNameFullPath, newNameFullPath);

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로 둘러싸십시오.


당신은 File.Move그것을 할 수 있습니다 .


다음을 추가하십시오.

namespace System.IO
{
    public static class ExtendedMethod
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
        }
    }
}

그리고...

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

  1. 첫 번째 솔루션

    System.IO.File.Move여기에 게시 된 솔루션을 하십시오 (표시된 답변 포함). 네트워크를 통해 장애 조치됩니다. 그러나 패턴 복사 / 삭제는 로컬 및 네트워크를 통해 작동합니다. 이동 솔루션 중 하나를 따르되 대신 복사로 바꿉니다. 그런 다음 File.Delete를 사용하여 원본 파일을 삭제합니다.

    Rename 메서드를 만들어 단순화 할 수 있습니다.

  2. 사용의 용이성

    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:\whatever\폴더에 b.txt.


새 파일로 복사 한 다음 System.IO.File클래스를 사용하여 이전 파일을 삭제할 수 있습니다 .

if (File.Exists(oldName))
{
    File.Copy(oldName, newName, true);
    File.Delete(oldName);
}

참고 : 이 예제 코드에서는 디렉토리를 열고 파일 이름에 열린 괄호와 닫힌 괄호가있는 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();
        }
    }
}

사용하다:

using System.IO;

string oldFilePath = @"C:\OldFile.txt"; // Full path of old file
string newFilePath = @"C:\NewFile.txt"; // Full path of new file

if (File.Exists(newFilePath))
{
    File.Delete(newFilePath);
}
File.Move(oldFilePath, newFilePath);

바라건대! 그것은 당신에게 도움이 될 것입니다. :)

  public static class FileInfoExtensions
    {
        /// <summary>
        /// behavior when new filename is exist.
        /// </summary>
        public enum FileExistBehavior
        {
            /// <summary>
            /// None: throw IOException "The destination file already exists."
            /// </summary>
            None = 0,
            /// <summary>
            /// Replace: replace the file in the destination.
            /// </summary>
            Replace = 1,
            /// <summary>
            /// Skip: skip this file.
            /// </summary>
            Skip = 2,
            /// <summary>
            /// Rename: rename the file. (like a window behavior)
            /// </summary>
            Rename = 3
        }
        /// <summary>
        /// Rename the file.
        /// </summary>
        /// <param name="fileInfo">the target file.</param>
        /// <param name="newFileName">new filename with extension.</param>
        /// <param name="fileExistBehavior">behavior when new filename is exist.</param>
        public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
        {
            string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
            string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
            string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);

            if (System.IO.File.Exists(newFilePath))
            {
                switch (fileExistBehavior)
                {
                    case FileExistBehavior.None:
                        throw new System.IO.IOException("The destination file already exists.");
                    case FileExistBehavior.Replace:
                        System.IO.File.Delete(newFilePath);
                        break;
                    case FileExistBehavior.Rename:
                        int dupplicate_count = 0;
                        string newFileNameWithDupplicateIndex;
                        string newFilePathWithDupplicateIndex;
                        do
                        {
                            dupplicate_count++;
                            newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
                            newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
                        } while (System.IO.File.Exists(newFilePathWithDupplicateIndex));
                        newFilePath = newFilePathWithDupplicateIndex;
                        break;
                    case FileExistBehavior.Skip:
                        return;
                }
            }
            System.IO.File.Move(fileInfo.FullName, newFilePath);
        }
    }

이 코드를 사용하는 방법?

class Program
    {
        static void Main(string[] args)
        {
            string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
            string newFileName = "Foo.txt";

            // full pattern
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
            fileInfo.Rename(newFileName);

            // or short form
            new System.IO.FileInfo(targetFile).Rename(newFileName);
        }
    }

이동도 똑같습니다 = 이전 항목 복사 및 삭제.

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);               
        }
    }

C #에 일부 기능이 없으면 C ++ 또는 C를 사용합니다.

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);
    }
}

참고 URL : https://stackoverflow.com/questions/3218910/rename-a-file-in-c-sharp

반응형