2009-10-21 23 views
0

我需要一些幫助來重命名位於/ 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? 

} 

} 

回答

1

你可以看看string.Split

循環遍歷目錄中的所有文件。在您使用列表中的第一個名字

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

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

這會給你兩個字符串數組。

你的新的文件名就變成了:

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 
} 
+0

謝謝克里斯。如果循環遍歷目錄而不是bulletedList,我的「foreach」語句會是什麼樣子。我將代碼塊從List轉換爲目錄對象。問候, – Doug 2009-10-21 23:03:10

+0

雖然安德烈的答案是一樣的,使用string.split對於這種特殊情況更加簡單。克里斯得到了接受的答案。感謝你們兩位。問候, – Doug 2009-10-22 16:03:31

1

其實你應該通過一個

遍歷每個文件的目錄中並重新命名一個要確定新的文件名,你可以使用類似:

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/

+0

感謝安德烈 - 什麼是使用RegEx通過String.split進行推理?我可以得到這些建議中的任何一個來工作,但想知道更多....關心,Doug – Doug 2009-10-21 22:53:11

+0

斯普利特工作正常,但正則表達式會給你更多的靈活性。在你的情況下很容易分裂,但是假設你想用一個更復雜的模式替換,如:012-123112-167-ab-128-bb.jpg。假設您想要替換可能在任何地方的第一組字母,您會怎麼做?正則表達式更適合這種情況。 – 2009-10-21 23:45:58

+0

好點。這意味着我必須回到最終用戶(公司經理),看看他們預見未來需求。問候, – Doug 2009-10-22 00:01:34