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

标签 c# file rename .net

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

关于c# - 重命名服务器目录中的图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1603795/

相关文章:

windows - 批量重命名文件夹结构

php - 强制从外部服务器下载并重命名

c# - 将 SMO 应用程序部署到未安装 SQL Server 2008 的工作站

c# - .Net Core - Entity Framework - MySQL > 未找到 UseMysql

c++ - 在 C++ 中读取非文本文件

java - 使用 new File(directory).mkdir() 创建文件时出错

linux - 根据文件名对 Bash 中的 271,568 个文件进行排序

javascript - 从 WebAPI 获取 PDF 并从 UI 下载,但数据已损坏

c# - SQL - 是否有更好的方法将用于 where 子句的键列表传递到存储过程中?

bash - 在 Ubuntu/Linux 中使用变量模式批量重命名文件名