【问题标题】:How to create a folder out of the first few letters of a filename?如何从文件名的前几个字母创建文件夹?
【发布时间】:2018-08-31 14:23:24
【问题描述】:

所以我检查了基本的东西,但我想做以下事情:

我有 5 个文件,比如说:X1_word_date.pdf、XX1_word_date.pdf 等...

我想创建一个文件夹结构,例如:C:\PATH\X1、C:\PATH\XX1 等...

那么如何将文件名中“_”前的第一个字母放入字符串中呢?

我的想法是我使用 Directory.CreateDirectory,然后将主路径和字符串组合起来,以便获得文件夹。

我该怎么做?帮助表示赞赏。

【问题讨论】:

  • 您要将文件移动到这些文件夹中吗?
  • 您好,您的解决方案不错。你需要的是学习基本的字符串操作。查看本教程(尤其是 Split 和 IndexOf 方法):String manipulation
  • 如果是两位数怎么办?喜欢 X23?
  • 文件名中第一个 _ 之前的第一部分是否与路径完全匹配?还是只是数字?
  • 如果你想要 _ 之前的任何内容,你可以将一个字符串拆分为一个变量,并使用目录创建,就像你说的,将目录的开始部分存储在一个变量中,然后添加之后的新目录。但是在尝试创建它之前检查目录是否存在

标签: c# file directory


【解决方案1】:
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]); 

这样的事情应该可以工作。使用Split() 也将允许处理大于 9 的数字

【讨论】:

  • 建议使用 Path.Combine 而不是串联。
  • 成功了!谢谢,但是如果我事先不知道这些字母怎么办?我已经尝试用 _word_.pdf 替换“X1_word_date.pdf”,但它说:非法字符...
【解决方案2】:

使用简单的字符串方法,例如 SplitSystem.IO.Path 类:

var filesAndFolders = files
.Select(fn => new
{
    File = fn,
    Dir = Path.Combine(@"C:\PATH", Path.GetFileNameWithoutExtension(fn).Split('_')[0].Trim())
});

如果您想创建该文件夹并添加文件:

foreach (var x in filesAndFolders)
{
    Directory.CreateDirectory(x.Dir); // will only create it if it doesn't exist yet
    string newFileName = Path.Combine(x.Dir, x.File);
    // we don't know the old path of the file so i can't show how to move
}

【讨论】:

  • 注意 [0] 处的 null
  • @ThierryV: String.Split 从不返回 null
  • @ThierryV 在什么情况下可以在 [0] 处获得 null?
  • 啊,我看到了,它永远不会为空:)。谢谢
【解决方案3】:

假设您的files 是一个List<string>,其中包含文件名 (X2_word_date.pdf,...)

files.ForEach(f => {
    var pathName=  f.Split('_').FirstOrDefault();
    if(!string.IsNullOrEmpty(pathName))
    {
        var directoryInfo = DirectoryInfo(Path.Combine(@"C:\PATH", pathName));
        if(!directoryInfo.Exists)
            directoryInfo.Create();

       //Then move this current file to the directory created, by FileInfo and Move method 
    }
})

【讨论】:

    【解决方案4】:

    或者使用正则表达式

                string mainPath = @"C:\PATH";
                string[] filenames = new string[] { "X1_word_date.pdf", "X2_word_date.pdf" };
                foreach (string filename in filenames)
                {
                    Match foldernameMatch = Regex.Match(filename, "^[^_]+");
                    if (foldernameMatch.Success)
                        Directory.CreateDirectory(Path.Combine(mainPath, foldernameMatch.Value));
                }
    

    【讨论】:

      【解决方案5】:

      仅从源目录和目标目录开始使用更大的图景。
      我们可以使用Directory.GetFiles列出我们需要移动的所有文件。
      在此列表中,我们首先使用GetFileName 隔离文件名。
      使用简单的String.Split,您就有了新的目录名称。
      Directory.CreateDirectory 将创建目录,除非它们已经存在。
      要移动文件,我们需要它的目标路径、目标目录路径和文件名的组合。

      string sourceDirectory = @"";
      string destDirectory = @"";
      
      string[] filesToMove = Directory.GetFiles(sourceDirectory); 
      
      foreach (var filePath in filesToMove) {
          var fileName = Path.GetFileName(filePath);
          var dirPath = Path.Combine(destDirectory, fileName.Split('_')[0]);
          var fileNewPath= Path.Combine(dirPath,fileName);
          Directory.CreateDirectory(dirPath);// If it exist it does nothing.
          File.Move(filePath, fileNewPath);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多