3 回答

TA贡献2003条经验 获得超2个赞
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]);
像这样的事情应该有效。使用Split()还将允许处理大于 9 的数字

TA贡献1851条经验 获得超5个赞
使用简单的字符串方法,如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
}

TA贡献1854条经验 获得超8个赞
假设你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
}
})
- 3 回答
- 0 关注
- 256 浏览
添加回答
举报