Skip to main content
 首页 » 编程设计

c#之重命名服务器目录中的图像文件

2024年02月24日14sxdcgaq8080

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