【问题标题】:I can't move/rename a directory with space at its end我无法移动/重命名结尾有空格的目录
【发布时间】:2016-01-22 00:43:15
【问题描述】:

我有一个包含名称末尾空格的文件夹和文件的大型目录,我正在尝试将具有该空格的目录重命名为不带空格的目录,以便另一个应用程序能够访问它。

我正在使用 C#(但如果有更好的选项可以解决该问题,请提出建议),这是我的整个代码:

using System;
using System.IO;
using System.Text.RegularExpressions;

namespace removing_spaces_in_directories_names
{
    class Program
    {
        public static string path = "../../../old_directory";
        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            WalkDirectoryTree(di);
            Console.ReadLine();
        }

        static void WalkDirectoryTree(System.IO.DirectoryInfo root)
        {
            if (root.Name != "old_directory")
            { renameDirectory(root); }
            DirectoryInfo[] diArr = root.GetDirectories();
            foreach(DirectoryInfo di in diArr)
            {
                WalkDirectoryTree(di);
            }
        }

        static void renameDirectory(System.IO.DirectoryInfo dir)
        {
            Console.WriteLine("renaming: " + dir.FullName);
            string newName = ReplaceLastOccurrence(dir.FullName, " ", "");
            if (Directory.Exists(dir.FullName) == false)
            {
                //dir.MoveTo(newName);
                String oldName = @"\\?\"+dir.FullName;
                Directory.Move(oldName,newName);
            }
        }

        public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
        {
            int place = Source.LastIndexOf(Find);

            if (place == -1)
                return Source;

            string result = Source.Remove(place, Find.Length).Insert(place, Replace);
            return result;
        }
    }
}

我已尝试按照here 的建议将“\?\”添加到文件夹名称的开头,但这不起作用,如果我添加它会出现错误:路径中的非法字符强>。

另一方面,如果我使用没有“\?\”字符的dir.MoveTo(newName);,我会收到错误:找不到路径“志愿者信息”的一部分

如果有的话,我该怎么办?也许会在 linux 而不是 windows 上运行这个应用程序帮助?

【问题讨论】:

    标签: c# directory


    【解决方案1】:

    对于您要重命名的每个目录(在这种情况下删除末尾的尾随空格),假设您的 DirectoryInfo 变量称为 di

    你想这样做:

    string oldName = di.FullName;
    string newName = oldName.TrimEnd();
    Directory.Move(oldName, newName);
    

    【讨论】:

    • 我试过了,但现在又出现了另一个错误:Source and destination path must be different. 如果我尝试完全更改 newName 的路径或名称,则会收到错误消息:Could not find a part of the path
    • 这可能意味着 oldName 没有尾随空格
    【解决方案2】:

    我在一个位于 linux 上的 PHP 应用程序中重写了它并且它工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-10
      • 2019-01-07
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多