我需要一些帮助来重命名位于/ 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?
}
}
谢谢克里斯。如果循环遍历目录而不是bulletedList,我的“foreach”语句会是什么样子。我将代码块从List转换为目录对象。问候, – Doug 2009-10-21 23:03:10
虽然安德烈的答案是一样的,使用string.split对于这种特殊情况更加简单。克里斯得到了接受的答案。感谢你们两位。问候, – Doug 2009-10-22 16:03:31