我需要一些帮助来重命名位于/ 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?

 }

}
有帮助吗?

解决方案

您可以查看 string.Split

遍历目录中的所有文件。

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

这将为您提供两个字符串的数组:

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

使用列表中的第一个名称。

您的新文件名将变为:

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
}

其他提示

实际上你应该迭代目录中的每个文件并逐个重命名

要确定新文件名,您可以使用以下内容:

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/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top