因此,我检查了基本的内容,但我想执行以下操作:
我有5个文件,例如:X1_word_date.pdf,XX1_word_date.pdf等...
我想创建一个文件夹结构,例如:C:\ PATH \ X1,C:\ PATH \ XX1等...
那么我该如何将文件名中“ _”之前的前几个字母放入字符串中?
我的想法是,我使用Directory.CreateDirectory,而不是结合主路径和字符串,以便获得文件夹。
我该怎么做?帮助表示赞赏。
答案 0 :(得分:3)
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]);
类似的事情应该起作用。使用Split()
还将允许处理大于9的数字
答案 1 :(得分: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
}
})
答案 2 :(得分:3)
使用简单的字符串方法,例如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
}
答案 3 :(得分:2)
或使用正则表达式
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));
}
答案 4 :(得分:0)
仅从Source和Destination目录开始使用更大的图片。
我们可以列出需要使用Directory.GetFiles移动的所有文件。
在此列表中,我们首先使用GetFileName隔离文件名。
使用简单的String.Split,您将拥有新的目录名称。
Directory.CreateDirectory将创建目录,除非它们已经存在。
要移动文件,我们需要其目标路径,目标目录路径和fileName的组合。
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);
}