如何使用文件名的前几个字母创建文件夹?

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

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

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

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

我的想法是我使用 Directory.CreateDirectory 而不是组合主路径和字符串,所以我得到了文件夹。

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


MM们
浏览 257回答 3
3回答

湖上湖

string fileName = "X1_word_date.pdf";string[] tokens = fileName.Split('_');string myPath = "C:\\PATH\\";Directory.CreateDirectory( myPath + tokens[0]); 像这样的事情应该有效。使用Split()还将允许处理大于 9 的数字

江户川乱折腾

使用简单的字符串方法,如Split和System.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}

哔哔one

假设你files是一个List<string>包含文件名 (X2_word_date.pdf,...)files.ForEach(f => {&nbsp; &nbsp; var pathName=&nbsp; f.Split('_').FirstOrDefault();&nbsp; &nbsp; if(!string.IsNullOrEmpty(pathName))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var directoryInfo = DirectoryInfo(Path.Combine(@"C:\PATH", pathName));&nbsp; &nbsp; &nbsp; &nbsp; if(!directoryInfo.Exists)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; directoryInfo.Create();&nbsp; &nbsp; &nbsp; &nbsp;//Then move this current file to the directory created, by FileInfo and Move method&nbsp;&nbsp; &nbsp; }})
打开App,查看更多内容
随时随地看视频慕课网APP