2009-10-21 83 views
0

我需要一些帮助来重命名位于/ images/graphicsLib /的目录中的某些图像。重命名服务器目录中的图像文件

/graphicsLib /中的所有图像名称都具有如下所示的命名约定: 400-60947.jpg。我们将该文件的“400”部分称为前缀,并将后缀称为“60957”部分。整个文件名称我们称之为sku。

所以,如果你看到/ graphicLib的内容/它看起来像:
400-60957.jpg
400-60960.jpg
400-60967.jpg
400-60968.jpg
402 -60988.jpg
402-60700.jpg
500-60725.jpg
500-60733.jpg
等等

使用C# & System.IO,基于文件名的前缀重命名所有图像文件的可接受方式是什么?用户需要能够输入当前前缀,查看匹配的/ graphicsLib /中的所有图像,然后输入新前缀以使所有这些文件都使用新前缀重命名。只有文件的前缀被重命名,文件名的其余部分需要保持不变。

我至今是:

//enter in current prefix to see what images will be affected by 
// the rename process, 
// bind results to a bulleted list. 
// Also there is a textbox called oldSkuTextBox and button 
// called searchButton in .aspx 


private void searchButton_Click(object sender, EventArgs e) 

{ 

string skuPrefix = oldSkuTextBox.Text; 


string pathToFiles = "e:\\sites\\oursite\\siteroot\\images\graphicsLib\\"; 

string searchPattern = skuPrefix + "*"; 

skuBulletedList.DataSource = Directory.GetFiles(pathToFiles, searchPattern); 

skuBulletedList.DataBind(); 

} 



//enter in new prefix for the file rename 
//there is a textbox called newSkuTextBox and 
//button called newSkuButton in .aspx 

private void newSkuButton_Click(object sender, EventArgs e) 

{ 

//Should I loop through the Items in my List, 
// or loop through the files found in the /graphicsLib/ directory? 

//assuming a loop through the list: 

foreach(ListItem imageFile in skuBulletedList.Items) 

{ 

string newPrefix = newSkuTextBox.Text; 

//need to do a string split here? 
//Then concatenate the new prefix with the split 
//of the string that will remain changed? 

} 

} 

回答

1

你可以看看string.Split

循环遍历目录中的所有文件。在您使用列表中的第一个名字

fileParts[0] -> "400" 
fileParts[1] -> "60957.jpg" 

string[] fileParts = oldFileName.Split('-'); 

这会给你两个字符串数组。

你的新的文件名就变成了:

if (fileParts[0].Equals(oldPrefix)) 
{ 
    newFileName = string.Format("(0)-(1)", newPrefix, fileParts[1]); 
} 

然后重命名的文件:

File.Move(oldFileName, newFileName); 

循环遍历目录中的文件:

foreach (string oldFileName in Directory.GetFiles(pathToFiles, searchPattern)) 
{ 
    // Rename logic 
} 
+0

谢谢克里斯。如果循环遍历目录而不是bulletedList,我的“foreach”语句会是什么样子。我将代码块从List转换为目录对象。问候, – Doug 2009-10-21 23:03:10

+0

虽然安德烈的答案是一样的,使用string.split对于这种特殊情况更加简单。克里斯得到了接受的答案。感谢你们两位。问候, – Doug 2009-10-22 16:03:31

1

其实你应该通过一个

遍历每个文件的目录中并重新命名一个要确定新的文件名,你可以使用类似:

String newFileName = Regex.Replace("400-60957.jpg", @"^(\d)+\-(\d)+", x=> "NewPrefix" + "-" + x.Groups[2].Value); 

要重命名文件,你可以使用类似:

File.Move(oldFileName, newFileName); 

如果你不熟悉正则表达式,你应该检查: http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

,并下载该软件初步实践: http://www.radsoftware.com.au/regexdesigner/

+0

感谢安德烈 - 什么是使用RegEx通过String.split进行推理?我可以得到这些建议中的任何一个来工作,但想知道更多....关心,Doug – Doug 2009-10-21 22:53:11

+0

斯普利特工作正常,但正则表达式会给你更多的灵活性。在你的情况下很容易分裂,但是假设你想用一个更复杂的模式替换,如:012-123112-167-ab-128-bb.jpg。假设您想要替换可能在任何地方的第一组字母,您会怎么做?正则表达式更适合这种情况。 – 2009-10-21 23:45:58

+0

好点。这意味着我必须回到最终用户(公司经理),看看他们预见未来需求。问候, – Doug 2009-10-22 00:01:34