Подтвердить что ты не робот

Переименование некоторых файлов в папке

У меня есть задача изменить имена некоторых файлов (то есть добавлять идентификатор к каждому имени динамически) в папку с помощью С#.

Пример: help.txt to 1help.txt

Как я могу это сделать?

4b9b3361

Ответ 1

Посмотрите FileInfo.

Сделайте что-то вроде этого:

void RenameThem()
{
    DirectoryInfo d = new DirectoryInfo("c:/dir/");
    FileInfo[] infos = d.GetFiles("*.myfiles");
    foreach(FileInfo f in infos)
    {
        // Do the renaming here
        File.Move(f.FullName, Path.Combine(f.DirectoryName, "1" + f.Name));
    }
}

Ответ 2

Функция, которую вы ищете, составляет File.Move(source, destination) пространства имен System.IO. Также рассмотрите класс DirectoryInfo (одного и того же пространства имен) для доступа к содержимому папки.

Ответ 3

Я просто отправлю это здесь, так как мне нужно было написать этот код для моих собственных целей.

using System;
using System.IO;

public static class FileSystemInfoExtensions
{
    public static void Rename(this FileSystemInfo item, string newName)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        FileInfo fileInfo = item as FileInfo;
        if (fileInfo != null)
        {
            fileInfo.Rename(newName);
            return;
        }

        DirectoryInfo directoryInfo = item as DirectoryInfo;
        if (directoryInfo != null)
        {
            directoryInfo.Rename(newName);
            return;
        }

        throw new ArgumentException("Item", "Unexpected subclass of FileSystemInfo " + item.GetType());
    }

    public static void Rename(this FileInfo file, string newName)
    {
        // Validate arguments.
        if (file == null)
        {
            throw new ArgumentNullException("file");
        }
        else if (newName == null)
        {
            throw new ArgumentNullException("newName");
        }
        else if (newName.Length == 0)
        {
            throw new ArgumentException("The name is empty.", "newName");
        }
        else if (newName.IndexOf(Path.DirectorySeparatorChar) >= 0
            || newName.IndexOf(Path.AltDirectorySeparatorChar) >= 0)
        {
            throw new ArgumentException("The name contains path separators. The file would be moved.", "newName");
        }

        // Rename file.
        string newPath = Path.Combine(file.DirectoryName, newName);
        file.MoveTo(newPath);
    }

    public static void Rename(this DirectoryInfo directory, string newName)
    {
        // Validate arguments.
        if (directory == null)
        {
            throw new ArgumentNullException("directory");
        }
        else if (newName == null)
        {
            throw new ArgumentNullException("newName");
        }
        else if (newName.Length == 0)
        {
            throw new ArgumentException("The name is empty.", "newName");
        }
        else if (newName.IndexOf(Path.DirectorySeparatorChar) >= 0
            || newName.IndexOf(Path.AltDirectorySeparatorChar) >= 0)
        {
            throw new ArgumentException("The name contains path separators. The directory would be moved.", "newName");
        }

        // Rename directory.
        string newPath = Path.Combine(directory.Parent.FullName, newName);
        directory.MoveTo(newPath);
    }
}

Ответ 5

Вы можете использовать File.Move, например:

string oldFilePath = Path.Combine( Server.MapPath("~/uploads"), "oldFileName");
string newFilePath = Path.Combine( Server.MapPath("~/uploads"), "newFileName");

File.Move(oldFilePath, newFilePath);

Ответ 6

В .NET Framework 4.0 я использую метод FileInfo.MoveTo(), который принимает только один аргумент

Просто для перемещения файлов мой метод выглядит следующим образом

private void Move(string sourceDirName, string destDirName)
{
    DirectoryInfo dir = new DirectoryInfo(sourceDirName);
    FileInfo[] files = null;

    files = dir.GetFiles();

    foreach (FileInfo file in files)
    {
        string temppath = Path.Combine(destDirName, file.Name);
        file.MoveTo(temppath);
    }
}

для переименования файлов мой метод выглядит следующим образом

private void Rename(string folderPath)
{
   int fileCount = 0;

   DirectoryInfo dir = new DirectoryInfo(folderPath);

   files = dir.GetFiles();

   foreach (FileInfo file in files)
   {
       fileCount += 1;
       string newFileName = fileCount.ToString() + file.Name;
       string temppath = Path.Combine(folderPath, newFileName);

       file.MoveTo(temppath);
   }
}

AS, который вы можете увидеть, чтобы переименовать файл, его синтаксис почти такой же, как и для Move it, просто нужно изменить filename перед использованием метода MoveTo().