서버 디렉토리에서 이미지 파일 이름을 바꿉니다
문제
/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
등...
사용 씨# & 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
이 소프트웨어를 Pratice로 다운로드하십시오.http://www.radsoftware.com.au/regexdesigner/